How can I use a script to create users in MongoDB?



You can use createUser() method for this. Following is the syntax −

db.createUser(    {       user: "yourUserName",       pwd: "yourPassword",       roles: [ { role: "read", db: "yourDatabaseName" } ]    } );

Let us create a user in MongoDB. Here, we are using database ‘test’ −

> db.createUser( ...    { ...       user: "David", ...       pwd: "David123456", ...       roles: [ { role: "read", db: "test" } ] ...    } ... );

This will produce the following output −

Successfully added user: {    "user" : "David",    "roles" : [       {          "role" : "read",          "db" : "test"       }    ] }
Updated on: 2019-07-30T22:30:26+05:30

321 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements