Computer >> Computer tutorials >  >> Programming >> MongoDB

Create a new user and set role in MongoDB


For this, use userAdminAnyDatabase since it gives all permission like admin. Following is the syntax −

use admin
db.createUser(
   {
      user: "yourUserName",
      pwd: "yourPassword",
      roles: [ { role: "yourRoleName", db: "yourDatabaseName" } ]
   }
)

Let us implement the above syntax to create a user role. Following is the query to create a user with role "userAdminAnyDatabase" −

> use admin
switched to db 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"
      }
   ]
}