Welcome to Techy Tunes !

Follow Me
With the introduction of the new 3.x drivers mongodb team introduced new methods for good reasons. This includes db authentication too. If you are writing a new application it is always better to use the latest apis. Also, it is always good to upgrade for the latest api for the sake of maintainability.

Lot's of articles explain how to connect to mongo db with java driver with deprecared methods in 2.x api. Here I explain how to do it with mongodb 3.x. If you already have mongo installed you can directly jump here

Install Mongo

Follow this link to install mongo db in ubuntu 16.04


Check mongo status

check whether the mongo service is running by command
service mongod status
Note the Active: active (running) in the output


Creating Users

  • To start with, make sure that the authentication is disabled in mongodb service. 
  • Generally, the mongo conf lies in /etc/mongod.conf
  • Check whether the following tag is present. If present make it disabled. If its absent, mongo is already in disabled authentication mode
 security: 
     authorization: disabled

After disabling authentication, restart the server
sudo service mongod restart

  • Login to mongo by just typing mongo in the command prompt
  • create user isuru in mydb database.
use mydb;
db.createUser(
  {
    user: "isuru",
    pwd: "mypwd",
    roles: [ { role: "dbOwner", db: "mydb" } ]
  })
  • Change "authorization" to "enabled" in the /etc/mongod.conf to enable authentication. 
  • Restart mongo

Login to Mongo with username and password

  • Login to mongo db with the new user
mongo  -u "isuru" -p "mypwd" --authenticationDatabase "mydb"


  • make sure to issue the command "use mydb" before you query any collection

Working with mongo db Java 3.x driver

How to authenticate mongodb with mongo java driver 3.x

  • This is how to connect with mongodb using username and password with java 3.x driver. Note that dbUser, dbName, dbPassword I get from configs
MongoDatabase getMongoDatabase() {
        MongoCredential credential = MongoCredential.createCredential(dbUser, dbName, dbPassword);
        ServerAddress serverAddress = new ServerAddress(dbHost);
        List credentialList = new ArrayList<>();
        credentialList.add(credential);

        MongoClient mongoClient = new MongoClient(serverAddress, credentialList);

        return mongoClient.getDatabase(dbName);
    }

There's some other tricky and interesting stuff on writing and fetching documents with mongodb. I'll update it here. Subscribe to keep you posted