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 to create a user in MongoDB v3?
To create a user in MongoDB v3, use the createUser() method. This allows you to create a user by specifying the username, password, and roles that assign specific permissions to databases.
Syntax
use admin
db.createUser(
{
user: "yourUserName",
pwd: "yourPassword",
roles: [ { role: "yourPermission", db: "yourDatabase" } ]
}
);
Example
Let us create a user named "Robert" with readWrite permissions on the "sample" database ?
use admin
db.createUser(
{
user: "Robert",
pwd: "robert",
roles: [ { role: "readWrite", db: "sample" } ]
}
);
This will produce the following output ?
Successfully added user: {
"user" : "Robert",
"roles" : [
{
"role" : "readWrite",
"db" : "sample"
}
]
}
Key Points
-
User creation must be done from the
admindatabase - Roles define what permissions the user has on specific databases
- Common roles include
read,readWrite,dbAdmin, anduserAdmin
Conclusion
The createUser() method in MongoDB v3 allows you to create users with specific roles and database permissions. Always switch to the admin database before creating users to ensure proper authentication setup.
Advertisements
