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?

leonigmig
  • 2,736
  • 3
  • 25
  • 21

5 Answers5

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.

Stephane Godbillon
  • 1,856
  • 13
  • 12
  • 1
    Are you sure about having to use `db.system`? Shouldn't `db.users.find(...).count()` do the same? – Philipp Oct 12 '12 at 11:53
  • 3
    `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. – Stephane Godbillon Oct 12 '12 at 12:41
  • Ah, ok. I thought the OP was talking about a normal collection named users, not about the users of the database itself. – Philipp Oct 12 '12 at 12:42
4

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

db.getUsers({filter: {'user': 'login'}})
Jean
  • 642
  • 5
  • 9
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.

infografnet
  • 3,749
  • 1
  • 35
  • 35
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.)

0

You can also use findOne

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

  • it will null if no user
  • it will return user if found
Linh
  • 57,942
  • 23
  • 262
  • 279