How to create MongoDB user on existing database with correct role?


To create a new user in MongoDB, use createUser(). Following is the query −

> db.createUser(
...    {
...       user: "John",
...       pwd: "123456",
...       roles: [ { role: "readWrite", db: "test" } ],
...       mechanisms: [ "SCRAM-SHA-256" ]
...    }
... )

This will produce the following output −

Successfully added user: {
   "user" : "John",
   "roles" : [
      {
         "role" : "readWrite",
         "db" : "test"
      }
   ],
   "mechanisms" : [
      "SCRAM-SHA-256"
   ]
}

Following is the query to show all users −

> db.getUsers();

This will produce the following output −

[
   {
      "_id" : "test.John",
      "user" : "John",
      "db" : "test",
      "roles" : [
         {
            "role" : "readWrite",
            "db" : "test"
         }
      ],
      "mechanisms" : [
         "SCRAM-SHA-256"
      ]
   }
]

Updated on: 03-Apr-2020

156 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements