定义
db.getUser(username, args)返回指定用户的用户信息。请在该指定用户的数据库中运行此方法。如果数据库中不存在该用户,
db.getUser()将返回null。db.getUser()方法具有以下参数:db.getUser( "<username>", { showCredentials: <Boolean>, showCustomData: <Boolean>, showPrivileges: <Boolean>, showAuthenticationRestrictions: <Boolean>, filter: <document> } ) Parameter类型说明username字符串
检索信息所针对的用户名称。
args文档
可选。指定附加参数的文档。
args文档支持以下字段:字段类型说明showCredentials布尔
可选。设置为
true,显示用户的密码哈希值。默认情况下,此字段为
false。showCustomData布尔
可选。设置为
false将省略输出中用户的customData。默认情况下,此字段为
true。5.2 版本中的新增功能。
showPrivileges布尔
可选。设置为
true以显示用户的完整权限集,包括继承角色的扩展信息。默认情况下,此字段为
false。如果查看所有用户,则不能指定此字段。
showAuthenticationRestrictions布尔
可选。设置为
true以显示用户的身份验证限制。默认情况下,此字段为
false。如果查看所有用户,则不能指定此字段。
filter文档
可选。指定
$match阶段条件的文档,用于为符合过滤条件的用户返回信息。db.getUser()会封装usersInfo: <username>命令。有关输出的详细信息,请参阅
usersInfo。
兼容性
此方法可用于以下环境中托管的部署:
重要
MongoDB Atlas集群不支持此命令。 有关Atlas支持所有命令的信息,请参阅不支持的命令。
MongoDB Enterprise:基于订阅、自我管理的 MongoDB 版本
MongoDB Community:源代码可用、免费使用且可自行管理的 MongoDB 版本
必需的访问权限
要查看其他用户的信息,必须对其他用户的数据库执行 viewUser 操作。
用户可查看自己的信息。
示例
以下操作返回有关 accounts 数据库中示例 appClient 用户的信息:
use accounts db.getUser("appClient")
示例输出:
{ _id: 'accounts.appClient', userId: UUID("1c2fc1bf-c4dc-4a22-8b04-3971349ce0dc"), user: 'appClient', db: 'accounts', roles: [], mechanisms: [ 'SCRAM-SHA-1', 'SCRAM-SHA-256' ] }
从输出中省略自定义数据
版本 5.2 中的新增功能:要省略 db.getUser()输出中用户的自定义数据,请将 showCustomData 选项设置为 false。
使用 createUser 命令在 products 数据库上创建名为 accountAdmin01 的用户:
db.getSiblingDB("products").runCommand( { createUser: "accountAdmin01", pwd: passwordPrompt(), customData: { employeeId: 12345 }, roles: [ { role: 'readWrite', db: 'products' } ] } )
用户包含一个 customData 字段 { employeeId: 12345 }。
要检索用户但从输出中省略自定义数据,请运行 db.getUser() 并将 showCustomData 设置为 false:
db.getSiblingDB("products").getUser( "accountAdmin01", { showCustomData: false } )
示例输出:
{ _id: 'products.accountAdmin01', userId: UUID("0955afc1-303c-4683-a029-8e17dd5501f4"), user: 'accountAdmin01', db: 'products', roles: [ { role: 'readWrite', db: 'products' } ], mechanisms: [ 'SCRAM-SHA-1', 'SCRAM-SHA-256' ] }