如何在 MongoDB 中重命名用户名?
要重命名用户,你需要使用 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 })
让我们验证一下是否已经使用 getUser() 创建了名为 ‘Larry’ 的用户 −
> db.getUser('Larry');
这将产生以下输出 −
{ "_id" : "admin.John", "user" : "Larry", "db" : "admin", "roles" : [ { "role" : "userAdminAnyDatabase", "db" : "admin" } ], "mechanisms" : [ "SCRAM-SHA-1", "SCRAM-SHA-256" ] }
如果你现在尝试获取旧用户名,那么将显示一个 null 值。我们来看看 −
> db.getUser('John');
这将产生以下输出 −
Null
广告