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

leonigmig picture leonigmig · Oct 12, 2012 · Viewed 14.6k times · Source

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?

Answer

Stephane Godbillon picture Stephane Godbillon · Oct 12, 2012

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.