要重命名用户,您需要使用update()和$set设置新的用户名。以下是语法-
db.system.users.update({"user":"yourOldUserName"}, {$set:{"user":"yourNewUserName"}});
首先,显示来自MongoDB数据库的所有用户-
> use admin; switched to db admin > db.getUsers();
这将产生以下输出-
[ { "_id" : "admin.Chris", "user" : "Chris", "db" : "admin", "roles" : [ { "role" : "readWrite", "db" : "test" } ], "mechanisms" : [ "SCRAM-SHA-1", "SCRAM-SHA-256" ] }, { "_id" : "admin.John", "user" : "John", "db" : "admin", "roles" : [ { "role" : "userAdminAnyDatabase", "db" : "admin" } ], "mechanisms" : [ "SCRAM-SHA-1", "SCRAM-SHA-256" ] }, { "_id" : "admin.Robert", "user" : "Robert", "db" : "admin", "roles" : [ { "role" : "readWrite", "db" : "sample" } ], "mechanisms" : [ "SCRAM-SHA-1", "SCRAM-SHA-256" ] } ]
现在将用户名从“ John”重命名为“ Larry”-
> db.system.users.update({"user":"John"}, {$set:{"user":"Larry"}}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
让我们验证是否已使用名称“ Larry”创建用户或未使用getUser()-
> db.getUser('Larry');
这将产生以下输出-
{ "_id" : "admin.John", "user" : "Larry", "db" : "admin", "roles" : [ { "role" : "userAdminAnyDatabase", "db" : "admin" } ], "mechanisms" : [ "SCRAM-SHA-1", "SCRAM-SHA-256" ] }
如果现在尝试获取旧的用户名,则将显示一个空值。让我们看到相同的-
> db.getUser('John');
这将产生以下输出-
Null