MongoDB – Specify Authentication and Target Database Separately in Connection URI

mongodbmongodb-3.4

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?

Best Answer

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