MongoDB 角色管理命令
角色管理命令用于为指定的用户定义角色。
MongoDB createRole命令
createRole命令分配一个角色并指定其优点。分配的角色适用于运行命令的数据库。如果角色在数据库中已经存在,该命令将返回重复角色错误。
语法:
{ createRole: "<new role>",
privileges: [
{ resource: { <resource> }, actions: [ "<action>", ... ] },
...
],
roles: [
{ role: "<role>", db: "<database>" } | "<role>",
...
],
authenticationRestrictions: [
{
clientSource: ["<IP>" | "<CIDR range>", ...],
serverAddress: ["<IP>" | "<CIDR range>", ...]
},
...
],
writeConcern: <write concern document>
}
命令字段:
字段 | 类型 | 描述 |
---|---|---|
createRole | 字符串 | createRole字段包含新角色的名称。 |
privileges | 数组 | 它包含要授予角色的权限。如果不想指定任何角色,请将其留空。 |
roles | 数组 | 它包含用于分配角色给用户的角色数组。 |
authentication Restrictions | 数组 | authentication字段限制了服务器对角色的强制执行。 |
writeConcern | 文档 | 它是应用于此操作的写入关注级别。 |
示例:
createRole 命令在 admin 数据库上创建 JavaTpointAdmin 角色。
db.adminCommand({ createRole: "JavaTpointAdmin",
privileges: [
{ resource: { cluster: true }, actions: [ "addShard" ] },
{ resource: { db: "config", collection: "" }, actions: [ "find", "update", "insert", "remove" ] },
{ resource: { db: "users", collection: "usersCollection" }, actions: [ "update", "insert", "remove" ] },
{ resource: { db: "", collection: "" }, actions: [ "find" ] }
],
roles: [
{ role: "read", db: "admin" }
],
writeConcern: { w: "majority" , wtimeout: 5000 }
})
MongoDB dropRole命令
MongoDB dropRole命令用于删除用户在运行该命令所在的数据库中定义的角色。
语法:
{
dropRole: "<role>",
writeConcern: { <write concern> }
}
Example:
This example remove the readPrice role from the products database.
use products
db.runCommand(
{
dropRole: "readPrices",
writeConcern: { w: "majority" }
}
)
MongoDB updateRole
update命令用于更新用户定义的角色。该命令必须在角色所属的数据库上运行。这个命令可以完全替换以前的字段值。
语法:
{
updateRole: "<role>",
privileges:
[
{ resource: { <resource> }, actions: [ "<action>", ... ] },
...
],
roles:
[
{ role: "<role>", db: "<database>" } | "<role>",
...
],
authenticationRestrictions:
[
{
clientSource: ["<IP>" | "<CIDR range>", ...],
serverAddress: ["<IP>", ...]
},
...
]
writeConcern: <write concern document>
}
示例:
db.adminCommand(
{
updateRole: "myClusterwideAdmin",
privileges:
[
{
resource: { db: "", collection: "" },
actions: [ "find" , "update", "insert", "remove" ]
}
],
roles:
[
{ role: "dbAdminAnyDatabase", db: "admin" }
],
writeConcern: { w: "majority" }
}
)
上述示例更新了admin数据库上的myClusterwideAdmin角色。
MongoDB grantPrivilagesToRole命令
这是一个非常重要的命令,用于向在运行该命令的数据库上添加一些额外的权限给用户定义的角色。
语法:
{
grantPrivilegesToRole: "<role>",
privileges: [
{
resource: { <resource> }, actions: [ "<action>", ... ]
},
...
],
writeConcern: { <write concern> }
}
示例:
use products
db.runCommand(
{
grantPrivilegesToRole: "service",
privileges: [
{
resource: { db: "products", collection: "" }, actions: [ "find" ]
},
{
resource: { db: "products", collection: "system.js" }, actions: [ "find" ]
}
],
writeConcern: { w: "majority" , wtimeout: 5000 }
}
)
上述示例向产品数据库中存在的服务角色授予了两个额外的权限。