admin 数据库中的 system.roles 集合存储了用户定义的角色。为了创建和管理这些用户定义的角色,MongoDB 提供了角色管理命令。
system.roles 架构
system.roles 集合中的文档具有以下模式:
{ _id: <system-defined id>, role: "<role name>", db: "<database>", privileges: [ { resource: { <resource> }, actions: [ "<action>", ... ] }, ... ], roles: [ { role: "<role name>", db: "<database>" }, ... ] }
system.roles 文档包含以下字段:
admin.system.roles.roleThe
rolefield is a string that specifies the name of the role.
admin.system.roles.dbThe
dbfield is a string that specifies the database to which the role belongs. MongoDB uniquely identifies each role by the pairing of its name (i.e.role) and its database.
admin.system.roles.privilegesThe
privilegesarray contains the privilege documents that define the privileges for the role.权限文档的语法如下:
{ resource: { <resource> }, actions: [ "<action>", ... ] } 每个权限文档都包含以下字段:
admin.system.roles.privileges[n].resourceA document that specifies the resources upon which the privilege
actionsapply. The document has one of the following form:{ db: <database>, collection: <collection> } or
{ cluster : true } 有关更多详细信息,请参阅有关自管理部署的资源文档。
admin.system.roles.privileges[n].actions允许对资源执行的操作大量。有关操作列表,请参阅特权操作。
示例
请考虑在admin数据库的system.roles集合中找到的以下示例文档。
用户定义的角色指定特权
以下是为 myApp 数据库定义的用户定义角色 appUser 的示例文档:
{ _id: "myApp.appUser", role: "appUser", db: "myApp", privileges: [ { resource: { db: "myApp" , collection: "" }, actions: [ "find", "createCollection", "dbStats", "collStats" ] }, { resource: { db: "myApp", collection: "logs" }, actions: [ "insert" ] }, { resource: { db: "myApp", collection: "data" }, actions: [ "insert", "update", "remove", "compact" ] }, { resource: { db: "myApp", collection: "system.js" }, actions: [ "find" ] }, ], roles: [] }
privileges大量列出了appUser角色指定的五种权限:
第一个权限允许对
myApp数据库中除系统集合之外的所有集合执行操作("find"、"createCollection"、"dbStats"、"collStats")。请参阅将数据库指定为资源。接下来的两个权限允许对
myApp数据库中的特定集合logs和data执行其他操作。 请参阅指定数据库集合作为资源。最后一个权限允许对
myApp数据库中的一个系统集合执行操作。 虽然第一个权限为find动作提供数据库范围的权限,但该动作应用用于myApp的系统集合。 要授予对系统集合的访问权限权限,权限必须显式指定该集合。 请参阅有关自管理部署的资源文档。
如空的roles数组所示,appUser 不会从其他角色继承任何额外权限。
用户定义的角色从其他角色继承
以下是为 myApp 数据库定义的用户定义角色 appAdmin 的示例文档:该文档显示 appAdmin 角色指定权限以及从其他角色继承权限:
{ _id: "myApp.appAdmin", role: "appAdmin", db: "myApp", privileges: [ { resource: { db: "myApp", collection: "" }, actions: [ "insert", "dbStats", "collStats", "compact" ] } ], roles: [ { role: "appUser", db: "myApp" } ] }
privileges 数组列出了 appAdmin 角色指定的权限。此角色具有单个权限,允许其对 myApp 数据库中的所有集合(不包括其系统集合)执行操作("insert"、"dbStats"、"collStats"、"compact")。请参阅将数据库指定为资源。
roles 数组列出由角色名称和数据库标识的角色, appAdmin 角色从中继承权限。