基于角色的访问控制:内置角色与自定义角色
学习者将分配 readWrite 和 dbAdmin 等内置角色,并为服务账户创建具有最小权限操作集的自定义角色。
基于角色的访问控制:内置角色与自定义角色 是 CoddyKit 上的免费 MongoDB Academy 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 MongoDB Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 MongoDB Academy 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
What Is Role-Based Access Control?
Role-Based Access Control (RBAC) is MongoDB's authorization model. Instead of granting individual permissions directly to users, you assign roles — named collections of privileges — to users. This makes permission management scalable: update a role and every user holding that role inherits the change automatically. MongoDB ships with a rich set of built-in roles covering the most common access patterns.
Built-In Database Roles
MongoDB provides several database-level roles that apply to a specific database. The most commonly used are: read (read all collections), readWrite (read + insert/update/delete), dbAdmin (schema management, index creation), and userAdmin (create/modify users in that database). These roles are database-scoped — a user with readWrite on myApp cannot access otherApp.
// Create a user with readWrite on one database only
use myApp
db.createUser({
user: 'appUser',
pwd: 'SecurePass!',
roles: [
{ role: 'readWrite', db: 'myApp' }
]
})
// Create a user with dbAdmin (can manage indexes but not data)
db.createUser({
user: 'dbaUser',
pwd: 'DbaPass!',
roles: [
{ role: 'dbAdmin', db: 'myApp' }
]
})Built-In Cluster-Wide Roles
Some built-in roles span all databases on a MongoDB instance. readAnyDatabase and readWriteAnyDatabase grant their respective permissions across every database. dbAdminAnyDatabase allows schema management everywhere. The most powerful is root, which has full access to everything — use it only for initial setup and emergency recovery, never for application accounts.
// Grant read-only access to all databases (reporting tool)
use admin
db.createUser({
user: 'globalReporter',
pwd: 'ReportPass!',
roles: [
{ role: 'readAnyDatabase', db: 'admin' }
]
})
// The root role — avoid for applications
// roles: [{ role: 'root', db: 'admin' }] // too powerful!The Principle of Least Privilege
Every MongoDB user should have exactly the permissions they need — no more. An API that only reads products should have read, not readWrite. A background job that archives documents should only be able to query and delete from the archive collection — not from all collections. Applying least privilege limits the blast radius of a compromised credential.
// Tightly scoped user for a product listing API
use admin
db.createUser({
user: 'productListingApi',
pwd: 'ProductApiPass!',
roles: [
{ role: 'read', db: 'catalog' } // read-only on catalog DB only
]
})Creating Custom Roles
When built-in roles are too broad, create a custom role using db.createRole(). A role definition lists specific privileges — each privilege is an action (e.g., find, insert, createIndex) on a resource (a specific database, collection, or cluster). Custom roles can also inherit from existing roles using the roles array.
// Custom role: can read orders and update order status only
use myApp
db.createRole({
role: 'orderProcessor',
privileges: [
{
resource: { db: 'myApp', collection: 'orders' },
actions: ['find', 'update']
}
],
roles: [] // no inherited roles
})Assigning Custom Roles to Users
Assign a custom role the same way you assign built-in roles — include it in the roles array when creating a user or grant it later with db.grantRolesToUser(). A user can hold multiple roles simultaneously, combining their permissions. MongoDB computes the union of all privileges from all assigned roles when authorizing each operation.
// Create user and assign custom role
use myApp
db.createUser({
user: 'fulfillmentWorker',
pwd: 'FulfillPass!',
roles: [
{ role: 'orderProcessor', db: 'myApp' }
]
})
// Grant an additional role to an existing user
db.grantRolesToUser('fulfillmentWorker', [
{ role: 'read', db: 'products' }
])Revoking Roles and Modifying Access
When an employee changes roles or a service is decommissioned, revoke unnecessary permissions promptly. db.revokeRolesFromUser() removes specific roles from a user without deleting the account. db.updateUser() lets you replace the entire roles array. Regularly audit users and their assigned roles with db.getUsers() to catch privilege creep.
// Revoke a specific role from a user
use myApp
db.revokeRolesFromUser('fulfillmentWorker', [
{ role: 'read', db: 'products' }
])
// Replace all roles for a user
db.updateUser('fulfillmentWorker', {
roles: [{ role: 'read', db: 'myApp' }] // demote to read-only
})Collection-Level Privilege Granularity
Custom roles can be scoped to a specific collection rather than an entire database. This allows fine-grained access control where, for example, a service can only read the products collection but has no access to users or orders in the same database. Collection-level scoping is achieved by specifying a collection name in the resource document.
// Role scoped to a single collection
use myApp
db.createRole({
role: 'catalogReader',
privileges: [
{
resource: { db: 'myApp', collection: 'products' },
actions: ['find']
}
],
roles: []
})Cluster Administration Roles
Several built-in roles govern cluster-level operations rather than data access. clusterMonitor grants read access to monitoring commands (useful for metrics exporters). clusterAdmin allows managing shards, replica sets, and global operations — very powerful, restrict carefully. backup and restore roles grant the specific permissions needed for mongodump and mongorestore without full admin rights.
// Backup user — can dump data but not administer users
use admin
db.createUser({
user: 'backupAgent',
pwd: 'BackupPass!',
roles: [
{ role: 'backup', db: 'admin' }
]
})
// Monitoring exporter user
db.createUser({
user: 'prometheusExporter',
pwd: 'MonitorPass!',
roles: [
{ role: 'clusterMonitor', db: 'admin' },
{ role: 'read', db: 'local' }
]
})Viewing Role Details and Inherited Privileges
Use db.getRole(roleName, { showPrivileges: true }) to see exactly which actions and resources a role grants, including inherited privileges from parent roles. This is essential for auditing — you can confirm that a custom role provides exactly the right permissions without accidentally granting broader access through inherited roles.
// Inspect a custom role's full privileges
use myApp
db.getRole('orderProcessor', { showPrivileges: true })
// List all custom roles in the current database
db.getRoles({ showBuiltinRoles: false })
// List all users and their roles
db.getUsers()RBAC in MongoDB Atlas
MongoDB Atlas implements RBAC through its Database Access panel. You can create database users with built-in or custom roles via the Atlas UI, Atlas CLI, or Atlas API. Atlas also supports temporary users that expire automatically after a set time — ideal for short-lived developer access or incident response. Additionally, Atlas can integrate with AWS IAM and LDAP for enterprise identity management.
Quick Check
Test your understanding of MongoDB & NoSQL Databases concepts from this lesson.
Lesson Recap
In this lesson you learned: built-in roles like read, readWrite, and dbAdmin cover common access patterns at database scope, custom roles let you define collection-level privileges with only the exact actions required, and principle of least privilege — each user and service account should hold only the permissions it genuinely needs. Next up we cover encryption at rest and TLS in transit.
常见问题解答
「基于角色的访问控制:内置角色与自定义角色」课时是免费的吗?
是的 — 「基于角色的访问控制:内置角色与自定义角色」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 MongoDB Academy 课程的其余内容,请升级到 CoddyKit PRO。 MongoDB Academy 课程共包含 4 节课。
「基于角色的访问控制:内置角色与自定义角色」这节课中我会学到什么?
学习者将分配 readWrite 和 dbAdmin 等内置角色,并为服务账户创建具有最小权限操作集的自定义角色。 你通过在浏览器中直接运行的动手代码来练习 MongoDB Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 MongoDB Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 MongoDB Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。
「基于角色的访问控制:内置角色与自定义角色」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 MongoDB Academy 课中编写并运行代码吗?
能。每节 MongoDB Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 身份验证机制:SCRAM 与 x.509
- 基于角色的访问控制:内置角色与自定义角色
- 静态数据加密与传输中的 TLS
- 客户端字段级加密