To create a user in MongoDB v3, use the createUser() method. This allows you to create a user and while creating you need to add user, password, and roles as well. These roles assign permissions. The syntax is as follows −
use admin db.createUser( { user: “yourUserName", pwd: "yourPassword", roles: [ { role: "yourPermission", db: "yourDatabase" } ] } );
Let us implement the above syntax in order to create a user In MongoDB v3 −
> use admin switched to db admin > db.createUser( ... { ... user: "Robert", ... pwd: "robert", ... roles: [ { role: "readWrite", db: "sample" } ] ... } ... );
Above, we have set the following for the new user −
User: Robert Password: robert Roles: readWrite This will produce the following output: Successfully added user: { "user" : "Robert", "roles" : [ { "role" : "readWrite", "db" : "sample" } ] }
We have successfully created a new user “Robert” above.