Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

MongoDB Tips and Tricks: Collection-Level Access Control

DZone's Guide to

MongoDB Tips and Tricks: Collection-Level Access Control

Learn about tips and tricks for collection-level access control while using MongoDB from Chris Chang, a developer advocate for MongoLab.

· Performance Zone
Free Resource

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 dbOwner role, 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.

Related Refcard:

Topics:
mongodb ,how-to ,access control

Published at DZone with permission of Chris Chang, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}