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

MongoDBDatabaseBig Data Analytics

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"
      ]
   }
]
raja
Published on 03-Apr-2020 16:31:56
Advertisements