MongoDB 命令行显示用户是否存在(对于 puppet 'unless' 子句)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12856420/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MongoDB command line to show if a user exists (for puppet 'unless' clause)
提问by leonigmig
We are using MongoDB user based authentication, and I want to quickly run a command to check whether a user has already been created in the database, in order that puppet won't repeatedly attempt to create the user.
我们正在使用基于 MongoDB 用户的身份验证,我想快速运行一个命令来检查数据库中是否已经创建了用户,以便 puppet 不会重复尝试创建用户。
Here is how we check if the replica set has initialised:
以下是我们如何检查副本集是否已初始化:
/usr/bin/mongo --host ${members[0]} --quiet --eval 'rs.status().ok' | grep -q 1
Is a similar trick possible with authentication? I've checked the documentation here http://www.mongodb.org/display/DOCS/dbshell+%28mongo%29+Referenceand I can't see a way of doing it?
身份验证是否可以使用类似的技巧?我已经在这里查看了文档http://www.mongodb.org/display/DOCS/dbshell+%28mongo%29+Reference 但我看不到这样做的方法?
回答by Stephane Godbillon
Yes, on a given DB, you can use db.system.users.find({user:'login'}).count()which will return 0 if the user does not exist.
是的,在给定的数据库上,db.system.users.find({user:'login'}).count()如果用户不存在,您可以使用which 将返回 0。
回答by infografnet
Today I just tried -uand -poptions for mongocommand and it worked for me:
今天,我只是想-u和-p用于选项mongo命令和它的工作对我来说:
mongo --port 27037 --quiet -u superuser -p pwd
--eval "db.system.users.find({user:'user3'}).count()" admin
Note the last "admin" arg - it is the name of database, to which you are authenticating.
请注意最后一个“admin”参数 - 它是您要对其进行身份验证的数据库的名称。
回答by Andy Leonard
To check if a user usernameexists:
检查用户是否username存在:
db.runCommand({ usersInfo: { user: "username", db: "admin" } }).users.length == 1
This will return trueif the user exists, and falseotherwise. (If the user was created in another database, replace adminwith the name of the database.)
true如果用户存在,这将返回,false否则将返回。(如果用户是在另一个数据库中创建的,请替换admin为该数据库的名称。)
回答by Phan Van Linh
You can also use findOne
你也可以使用 findOne
db.system.users.findOne({user:'login'})
db.system.users.findOne({user:'login'})
- it will
nullif no user - it will return user if found
null如果没有用户,它会- 如果找到,它将返回用户
回答by Jean
It feels that this method has been deprecated, I needed the following command to work:
感觉这个方法已经被弃用了,我需要以下命令才能工作:
db.getUsers({filter: {'user': 'login'}})

