MongoDB tips & tricks: Collection-level access control

As your database or project grows, you may be tasked with configuring access controls to allow different stakeholders access to the database. Rather than create a new user with full database privileges, it may be more appropriate to create a user that only has access to the data or collections they need. This allows users to query against the collections you define and limits their access to the rest of the database.

Here's a step-by-step example that demonstrates how to set up collection-level access control. This example will create a user named "finance" on the "acme" database. The "finance" user will only have "find" (read) access to the "billing" collection.

Step 1. Connect to the "acme" database using an existing user

> mongo ds123456.mlab.com:12345/acme -u dba -p password

Note that the "dba" user will need the userAdmin role to create and modify roles and users on the "acme" database. By default, mLab database users created through the UI are granted the dbOwnerrole, which combines the privileges granted by the readWrite, dbAdmin, and userAdmin roles.

Step 2. Create a new user-defined role for the "billing" collection

> db.createRole({ role: "readBillingOnly", privileges: [ { resource: { db: "acme", collection: "billing" }, actions: [ "find" ] } ], roles: [] })]

You can also add more privilege actions to the "actions" array, such as "insert" or "update".

Step 3. Create a new user named "finance" with the role you just created

> db.createUser({ user: "finance", pwd: "password", roles: [ { role: "readBillingOnly", db: "acme" } ] })

Alternatively, if the user already exists, you can use the grantRolesToUser() method:

> db.grantRolesToUser("finance", [ { role: "readBillingOnly", db: "acme" } ])<

 

And that's it! You now have a user named "finance" that has read-only access on the "billing" collection in the "acme" database.