16

I am using this connection uri to connect to mongodb: mongodb://user:password@localhost/admin. It will use admin as bot authentication and target database. How can I make the uri to use admin as authentication but allow me to connect to a different database? Please see below command as an example:

mongo --host localhost -u user -p password --authentication admin test

the above command will use admin as the authentcation database but connect to test database. how can I do the same thing on uri?

Joey Yi Zhao
  • 577
  • 3
  • 9
  • 23

2 Answers2

34

Yes.. Easily!

mongo "mongodb://test:testpwd@localhost/test?authSource=admin"
MongoDB shell version v3.4.6
connecting to: mongodb://test:testpwd@localhost/test?authSource=admin
MongoDB server version: 3.4.6
MongoDB> db
test
MongoDB> 

You put your destination DB at end of "base" string and add authentication db to parameter authSource

JJussi
  • 5,873
  • 1
  • 18
  • 19
4

Ref:

https://docs.mongodb.com/manual/reference/connection-string/#connections-connection-options

You will need to use below format and do not need to use admin database.

mongodb://user:password@localhost/test?authSource=admin

/database Optional. The name of the database to authenticate if the connection string includes authentication credentials in the form of username:password@. If /database is not specified and the connection string includes credentials, the driver will authenticate to the admin database.

Make sure you have a user in test database. See section 6 of this document.

Enable Auth

Create additional users as needed for your deployment.

The database where you create the user (in this example, test) is that user’s authentication database. Although the user would authenticate to this database, the user can have roles in other databases; i.e. the user’s authentication database does not limit the user’s privileges.

use test
db.createUser(
  {
    user: "myTester",
    pwd: "xyz123",
    roles: [ { role: "readWrite", db: "test" },
             { role: "read", db: "reporting" } ]
  }
)
SqlWorldWide
  • 13,687
  • 3
  • 30
  • 54