如何在 MongoDB 2.4 中向现有用户添加角色

Mar*_*ter 4 mongodb

我花了一个小时试图挖掘 MongoDB 的在线文档,当用户管理命令不断变化时,该文档对于 2.4 版本来说相当糟糕。

我在 mongoDB 2.4.11 中发现了这一点

db.addUser( { user: "...", pwd: "...", roles: [ ... ] } ) 
Run Code Online (Sandbox Code Playgroud)

作品。但我找不到任何更新用户角色的命令示例,并且当我尝试覆盖现有用户时收到此错误消息:

 User already exists with that username/userSource combination at src/mongo/shell/db.js:125
Run Code Online (Sandbox Code Playgroud)

所以我被困住了。

(作为奖励,我如何在 2.4 中从现有用户中删除角色?)

当我尝试时

db.grantRolesToUser( "myself", [  {role: "clusterAdmin"} ] )
Run Code Online (Sandbox Code Playgroud)

如 v2.6 中所述,我得到:

TypeError: Property 'grantRolesToUser' of object admin is not a function
Run Code Online (Sandbox Code Playgroud)

所以在 2.4 中不起作用。

Tar*_*han 7

2021 年更新

MongoDB 版本:4.4.2

您可以使用以下命令向现有用户添加角色db.grantRolesToUser()

官方语法:db.grantRolesToUser( "<username>", [ <roles> ], { <writeConcern> } )

使用以下命令,您可以授予对除本地配置之外的所有数据库的读写访问权限

> use admin;
> db.grantRolesToUser('user1', ['readWriteAnyDatabase']);
Run Code Online (Sandbox Code Playgroud)

但是,如果您只想授予特定数据库(例如帐户数据库)的读写权限,您可以按如下方式操作

use admin;
db.grantRolesToUser('user1', [{ role: 'readWrite', db: 'account' }]);
Run Code Online (Sandbox Code Playgroud)

MongoDB 参考:https://docs.mongodb.com/manual/reference/method/db.grantRolesToUser/