Database.RunCommand()
是为了方便调用MongoDB的runCommand()
函数,也就是说,它是一个助手来运行指定的database commands.
也就是说,您在mongoshell 中调用的getUser()
函数是一个函数,而不是一个命令.
但是有一个usersInfo
命令可以让你得到相同的数据.其语法为:
db.runCommand(
{
usersInfo: <various>,
showCredentials: <Boolean>,
showCustomData: <Boolean>,
showPrivileges: <Boolean>,
showAuthenticationRestrictions: <Boolean>,
filter: <document>,
comment: <any>
}
)
以下是执行此usersInfo
命令的方法:
var op bson.M
cmd := bson.D{{Key: "usersInfo", Value: bson.M{
"user": "testuser",
"db": "admin",
}}}
err = clientInfo.Database(db).RunCommand(ctx, cmd).Decode(&op)
请注意,usersInfo
文档的值为various specifications,例如:
{ usersInfo: 1 }
返回有关运行该命令的数据库中的用户的信息.
mongosh
为此命令调用提供db.getUsers()
帮助器.
{ usersInfo: <username> }
返回有关运行该命令的数据库中存在的特定用户的信息.
mongosh
为此命令调用提供db.getUser()
帮助器.
{ usersInfo: { user: <name>, db: <db> } }
返回有关名称和数据库指定的用户的信息.
{ usersInfo: [ { user: <name>, db: <db> }, ... ] }
{ usersInfo: [ <username1>, ... ] }
返回有关指定用户的信息.
{ forAllDBs: true }
返回有关所有数据库中的用户的信息.
如您所见,getUser()
命令是{ usersInfo: <username> }
的简写,您可以这样调用它:
var op bson.M
cmd := bson.D{{Key: "usersInfo", Value: "testuser"}}
err = clientInfo.Database(db).RunCommand(ctx, cmd).Decode(&op)
如果需要有关多个用户的信息,当然可以使用数组:
cmd := bson.D{{Key: "usersInfo", Value: []string{"testuser", "anotheruser"}}}