63

I am running mongo 2.2.2 on osx.

When I do the following authentication is going fine:

$ mongo
>> use admin
>> db.auth("uname", "password")

log:

Thu Mar  7 13:51:08 [initandlisten] connection accepted from 127.0.0.1:63474 #10 (4 connections now open)
Thu Mar  7 13:51:08 [conn10]  authenticate db: admin { authenticate: 1, nonce: "123", user: "uname", key: "456" }

However when I try to authenticate directly from the commandline:

$ mongo admin -u uname -p password

I get the following error:

Thu Mar  7 14:25:52 [initandlisten] connection accepted from 127.0.0.1:63939 #12 (5 connections now open)
Thu Mar  7 14:25:52 [conn12]  authenticate db: admin { authenticate: 1, nonce: "789", user: "uname", key: "147" }
Thu Mar  7 14:25:52 [conn12] auth: key mismatch uname, ns:admin
Thu Mar  7 14:25:52 [conn12] end connection 127.0.0.1:63939 (4 connections now open)

Does anyone know what causes this?

RickyA
  • 15,465
  • 5
  • 71
  • 95

5 Answers5

136

A password containing special characters, especially the dollar sign, has to be put in single quotes to protect them from the command shell:

$ mongo admin -u uname -p 'password'
ronasta
  • 2,519
  • 1
  • 15
  • 8
  • As explained [here](http://www.howtogeek.com/howto/29980/whats-the-difference-between-single-and-double-quotes-in-the-bash-shell/) – RickyA Apr 07 '13 at 09:54
  • 55
    To prevent exposing password to bash history, use `mongo admin -u uname -p` which will prompt you the password – Kimmo Dec 10 '14 at 11:45
  • 1
    @Kimmo Your comment is an answer in its own right. The password prompt you get with `-p` does not require protecting/escaping special characters, so the password can just be entered with no quote marks. I'll upvote that answer, which includes the added security bonus! – WAF Jan 11 '17 at 18:07
  • could not imagine how much official documents is confusing for this basic command! – Bheid Aug 25 '21 at 13:23
  • I needed to put the password in double quotation marks, single did not work – Berger Jun 07 '23 at 12:03
58

You have to use the --authenticationDatabase to indicate mongodb where to find the user you have created. For example:

mongo admin -u uname -p 'password' --authenticationDatabase admin
splash
  • 13,037
  • 1
  • 44
  • 67
user6155548
  • 581
  • 4
  • 2
2

This is the way to access an authenticate MongoDB database from terminal

mongo -u user_name -p "your_password" host_name/database_name

Ex:

mongo -u hasib -p "123456" localhost/my_db
Hasib Kamal Chowdhury
  • 2,476
  • 26
  • 28
1

You could also connect using the mongo connection URL as follow:

mongo "mongodb://<user>:<password>@<host: 127.0.0.1>:<port: 27017>/<db_name>?authSource=admin"
  • The db_name is optional.
  • The host is usually 127.0.0.1 if you are connection to localhost.
  • The port is usually 27017.
kimy82
  • 4,069
  • 1
  • 22
  • 25
-9

To Login to MongoDB Via Command Line do the following

$ mongo admin -u 'username' -p 'Password'
hakamairi
  • 4,464
  • 4
  • 30
  • 53