How to Add a New User to a MongoDB Database

After you’ve installed MongoDB, you will want to create separate users for each database to avoid vulnerabilities if any of the users gets compromised. This MongoDB tutorial shows how.

Matthias Hagemann
2 min readNov 9, 2018

If you haven’t installed MongoDB on your server yet, please follow my MongoDB installation guide here. I personally run MongoDB on a DigitalOcean droplet which was really easy to install. If you like, you can give it a try with a $100 credit by simply following this link:

Multiple Database Users vs. Single User

Should you maintain multiple database users or a single user with access to all databases? I highly recommend to keep them separate (one user per database). If any of your sites has a vulnerability and gets compromised, someone may use it to gain access to all your other databases. Using a single user puts every other database in danger. If users are restricted to merely one database each, you can be assured that other sites won’t be affected.

Enter the MongoDB shell with your administration credentials via this command in your terminal:

$ mongo -u 'your_username' -p 'your_password' --authenticationDatabase 'admin'

You should now see a new line with a > sign, meaning that you can start typing your MongoDB queries. Enter the database you want to add a new user for. Don’t worry about creating that database first because it will be created on the fly.

use your_new_database

Create a New MongoDB Database User

You have now switched to the database ‘your_new_database’. Create a new user for that database:

db.createUser({
user: 'new_username',
pwd: 'new_password',
roles: [
{ role: 'readWrite', db: 'your_new_database' }
]
})

I’m giving the new user merely permission to read and write into the database, hence the readWrite role which is well-documented in MongoDB’s docs.

--

--