In Part 1 of this series, we stepped through the process to create MongoDB system users: admin, MMS monitoring agent, and MMS backup agent users. We now look at ways to create MongoDB application users – the accounts that our applications uses to authenticate with MongoDB.

Application isolation

For example, suppose we have two applications, app1 and app2, that share the same MongoDB deployment (which might be a standalone, replica set, or sharded cluster). We want to ensure that each application can only read and write to its own set of data for integrity, privacy, and security reasons. So let’s use db.createUser() to assign the dbOwner role to the respective databases:

Let’s test that this works by spinning up a clean MongoDB instance in a terminal window:

Now save the user creation script above to create-app-users-1.js and execute in another terminal window:

Restart MongoDB with authentication enabled by first terminating the current instance by pressing Ctrl-c and running:

In another terminal window, connect via mongo shell without authentication and try to read/write the app1 database:

It fails as expected. Now repeat while authenticated as the app1 user:

Works as expected. Now try the same thing with the app2 database while still authenticated as app1:

It fails as expected, so now we know our application users are set up properly.

Application user lockdown

Granting dbOwner to the application user might be a bit too much for some. For example, not granting index creation permissions will help prevent accidentally foreground index creation, which locks the database until completion. It may even be desirable to whitelist collections that can be read and written to, in order protect against code typos or mistakenly dropping the wrong collections. Or perhaps allow only inserts to a log or audit collection to prevent tampering. To do so, we create a custom role and assign that to our new app3 user:


Adapt the script according to your needs and refer the MongoDB documentation for details. In particular, see Built-in Roles, Privilege Actions, db.createUser(), and db.createRole().