Authenticate to Mongo Database that isn’t “admin”

If you have set up your Mongo instance by adding a user to the “admin” database to authenticate against, you may of run into some confusion about how you connect & authenticate against another database on that server.

Let’s say you are trying to use the “local” database… If you using command line, you would need to add the parameter –authenticationDatabase. So your connection would look something like:

mongo myserver.com --username martin.milsom --authenticationDatabase admin -p myPassword

The extra parameter lets Mongo know where the user is to authenticate against.

Now, if you are using the C# driver for this, as I was, then the answer is to include the same parameter in the connection URL, for example:

var connectionString = "mongodb://martin.milsom:myPassword@myServer.com:27017/?authenticationDatabase=admin";
var database = new MongoClient(connectionString).GetDatabase("local");

Note here, the Url Parameter "?authenticationDatabase=admin" is how you add the parameter.