10

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?

19

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

  • Yep, this is exactly what i am looking for. Thanks – Zhao Yi Sep 14 '17 at 5:32
2

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" } ]
  }
)
  • I have tried this uri but it doesn't work. Because it tries to use test as the authentication database which is not correct. I need to use admin as authentication database and connect to test database. – Zhao Yi Sep 13 '17 at 2:28
  • Modified answer. – SqlWorldWide Sep 13 '17 at 2:43
  • Thanks for your response. But I don't want to change the user role on the database instance. Is there any solution not to make any change on the instance? – Zhao Yi Sep 13 '17 at 4:28
  • That is how it is designed by MongoDB. – SqlWorldWide Sep 13 '17 at 9:56
  • Does this mean I can't achieve this by mongo uri? – Zhao Yi Sep 13 '17 at 9:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.