Physical Address

304 North Cardinal St.
Dorchester Center, MA 02124

Create new user and grant it access to single database – MongoDB

Today we’ll create a new user and grant it access to a single database in MongoDB.

Start off by logging into mongodb with your admin/root user

mongo -u 'username' -p 'password' --authenticationDatabase 'admin'

You’ll land at a prompt like below if successfully authenticated

mongo terminal prompt

Issue the following to create a new user, replace the placeholders with your

db.createUser({user: 'new-username',pwd: 'new-password',roles: [{ role: 'readWrite', db: 'new-database'}]});

The prompt will return with “Successfully added user” if successful

That’s it, try logging in using the new credentials:

mongo -u 'new-username' -p 'new-password' --authenticationDatabase 'new-database'

To verify the credentials, issue the following to see how many databases show up

show databases

The prompt should return only one database followed by it’s size.