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
Create a new user and set role in MongoDB
To create a new user and set their role in MongoDB, use the createUser() method. The userAdminAnyDatabase role provides comprehensive administrative privileges across all databases.
Syntax
use admin
db.createUser(
{
user: "yourUserName",
pwd: "yourPassword",
roles: [ { role: "yourRoleName", db: "yourDatabaseName" } ]
}
)
Example
Create a user with the "userAdminAnyDatabase" role ?
use admin
db.createUser(
{
user: "David Miller",
pwd: "123456",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
}
)
This will produce the following output ?
Successfully added user: {
"user" : "David Miller",
"roles" : [
{
"role" : "userAdminAnyDatabase",
"db" : "admin"
}
]
}
Key Points
- Always switch to the admin database before creating administrative users
- The
userAdminAnyDatabaserole allows managing users across all databases - Multiple roles can be assigned by adding them to the roles array
Conclusion
Use db.createUser() in the admin database to create users with specific roles. The userAdminAnyDatabase role provides broad administrative privileges for user management across all databases.
Advertisements
