MongoDB command line to show if a user exists (for puppet 'unless' clause)
Asked Answered
E

5

11

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.

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+Reference and I can't see a way of doing it?

Efflorescence answered 12/10, 2012 at 9:49 Comment(0)
B
20

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.

Blaubok answered 12/10, 2012 at 10:4 Comment(3)
Are you sure about having to use db.system? Shouldn't db.users.find(...).count() do the same?Cottage
db.users.find(...).count() will return the number of documents that are stored in the users collection. This collection is not special and is not related to the MongoDB Authentication process.Blaubok
Ah, ok. I thought the OP was talking about a normal collection named users, not about the users of the database itself.Cottage
I
4

It feels that this method has been deprecated, I needed the following command to work:

db.getUsers({filter: {'user': 'login'}})
Indigestible answered 6/9, 2019 at 9:58 Comment(0)
T
2

Today I just tried -u and -p options for mongo command and it worked for me:

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.

Ternion answered 22/10, 2014 at 7:44 Comment(0)
E
0

To check if a user username exists:

db.runCommand({ usersInfo: { user: "username", db: "admin" } }).users.length == 1

This will return true if the user exists, and false otherwise. (If the user was created in another database, replace admin with the name of the database.)

Electrosurgery answered 31/7, 2018 at 18:30 Comment(0)
K
0

You can also use findOne

db.system.users.findOne({user:'login'})

  • it will null if no user
  • it will return user if found
Kentonkentucky answered 21/4, 2019 at 6:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.