Create User

MongoDB provides role-based access control. A user is granted one or more roles that determine the user’s access or privileges to MongoDB resources and the actions that a user can perform.

Syntax:-

> db.createUser(
{	
user: "userName",
pwd: "userPassword",
roles:[{role: "roleName" , db:"DBName"}
]
})

Note:- roles are read and readWrite

read:- User can access only for read the data from the database.

readWrite:- User can access for read and modify the database.

Example:- If user can access only read the database.

> db.createUser(
{	
user: "userName",
pwd: "userPassword",
roles:[{role: "read" , db:"DBName"}
]
})

Example:- If user can access read and modify the database.

> db.createUser(
{	
user: "userName",
pwd: "userPassword",
roles:[{role: "readWrite" , db:"DBName"}
]
})

Note:- A user can have different role for differnt database like

> db.createUser(
{	
user: "userName",
pwd: "userPassword",
roles:[{role: "readWrite" , db:"DBName1"},
       {role: "read" , db:"DBName2"}
]
})