Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How can I use a script to create users in MongoDB?
You can create users in MongoDB using the createUser() method. This method allows you to define username, password, and specific roles for database access control.
Syntax
db.createUser(
{
user: "yourUserName",
pwd: "yourPassword",
roles: [ { role: "roleType", db: "databaseName" } ]
}
);
Example
Let us create a user named "David" with read access to the "test" database ?
db.createUser(
{
user: "David",
pwd: "David123456",
roles: [ { role: "read", db: "test" } ]
}
);
This will produce the following output ?
Successfully added user: {
"user" : "David",
"roles" : [
{
"role" : "read",
"db" : "test"
}
]
}
Common Role Types
- read ? Read-only access to the database
- readWrite ? Read and write access to the database
- dbAdmin ? Database administration privileges
- userAdmin ? User management privileges
Conclusion
The createUser() method provides a straightforward way to create users with specific roles and database permissions. Always assign appropriate roles based on the user's required access level for security purposes.
Advertisements
