Docs 菜单
Docs 主页
/
MongoDB Manual
/ / /

db.getUser()

在此页面上

  • 定义
  • 必需的访问权限
  • 举例
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

要查看其他用户的信息,必须对其他用户的数据库执行 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' ]
}

后退

db.dropAllUsers