0
0
MongoDBquery~5 mins

Role-based access control in MongoDB

Choose your learning style9 modes available
Introduction

Role-based access control helps keep data safe by giving users only the permissions they need.

When you want to let some users read data but not change it.
When you want to allow only certain users to add or delete data.
When you need to control who can manage database settings.
When you want to organize users by their job roles and assign permissions accordingly.
Syntax
MongoDB
db.createRole({
  role: "roleName",
  privileges: [
    {
      resource: { db: "databaseName", collection: "collectionName" },
      actions: ["action1", "action2"]
    }
  ],
  roles: [{ role: "otherRole", db: "admin" }]
})
Use db.createRole() to make a new role with specific permissions.
The privileges array defines what actions the role can do on which resources.
Examples
This role lets users only read data from the 'products' collection in the 'shop' database.
MongoDB
db.createRole({
  role: "readOnly",
  privileges: [
    {
      resource: { db: "shop", collection: "products" },
      actions: ["find"]
    }
  ],
  roles: []
})
This role allows full control over the 'products' collection for managing items.
MongoDB
db.createRole({
  role: "productManager",
  privileges: [
    {
      resource: { db: "shop", collection: "products" },
      actions: ["find", "insert", "update", "remove"]
    }
  ],
  roles: []
})
This role inherits permissions from built-in roles 'readWrite' and 'dbAdmin'.
MongoDB
db.createRole({
  role: "admin",
  privileges: [],
  roles: [{ role: "readWrite", db: "admin" }, { role: "dbAdmin", db: "admin" }]
})
Sample Program

This example creates a role that allows reading reports, assigns it to user 'alice', and then checks her roles.

MongoDB
db.createRole({
  role: "reportViewer",
  privileges: [
    {
      resource: { db: "sales", collection: "reports" },
      actions: ["find"]
    }
  ],
  roles: []
})

// Assign the role to a user
use sales
db.grantRolesToUser("alice", [{ role: "reportViewer", db: "sales" }])

// Check user roles
db.getUser("alice")
OutputSuccess
Important Notes

Always assign the least permissions needed to keep data safe.

Roles can include other roles to combine permissions easily.

Use db.getUser() to check what roles a user has.

Summary

Role-based access control lets you manage who can do what in your database.

Create roles with specific permissions using db.createRole().

Assign roles to users to control their access safely and clearly.