How To Create A New User In MongoDB

In MongoDB, you can create users that each have their own privileges so they can access certain databases or have the ability to change certain settings, or you can give them total control over all databases and settings (only the database administrator should have this privilege to maintain an acceptable level of security).

To create a new user in MongoDB using the ‘mongosh’ command line/MongoDB shell, you can use the following command, but change the parameters to reflect the permissions and credentials needed by your user:

Create A User With Unlimited Privileges In MongoDB

db.createUser( {user: "yourusername", pwd: "yourpassword", roles: [ {role: "userAdminAnyDatabase", db: "admin"}, "readWriteAnyDatabase" ]} )

The command above creates a user with the username ‘yourusername’ and password ‘yourpassword’. Always use unique usernames and ensure that your passwords are both unique and strong, unlike the dummy password shown above. The role ‘userAdminAnyDatabase’ is broad and allows the user to control all of your MongoDB databases. If the user doesn’t need access to all databases, then a much safer approach is to only provide them with the database that they are supposed to have access to. Here’s an example of how to create a user in MongoDB with limited privileges by setting ‘db‘ to the database they should have access to and setting ‘role‘ to ‘readWrite’.

Create A New User With Limited Privileges In MongoDB

db.createUser( {user: "test1", pwd: "test1", roles: [ {role: "readWrite", db: "testdb1"} ] } )

Let us now try this with a more sensible username and password. Passwords should be more than 8 characters long and contain a combination of upper and lowercase letters, numbers, and optionally symbols if you wish. It is not advisable to use short, easy-to-remember passwords. Generate a strong, hard-to-crack password with a password generator (you can do this in Bitwarden with a few clicks) and store the password in a secure location.

db.createUser( {user: "sallyhb1502", pwd: "J*sNHZ3*3bcn7wxHy", roles: [ {role: "readWrite", db: "testdb1"} ] } )

Learn more about the options you have when creating users

You should see  ‘ok: 1’ if the operation was successful. You can also show all users in that database using the ‘db.getUsers()’ command as shown below:

How to create a new user in MongoDB