-1

I have MongoConnectionUtils this file I have dependecy below mongo-java-driver

<dependency>
        <groupId>org.mongodb</groupId>
        <artifactId>mongo-java-driver</artifactId>
        <version>3.0.0</version>
    </dependency>


  public class MongoConnectionUtils {
                private static MongoDatabase db;
        public synchronized static MongoDatabase getConnection() {

            if (db != null) {
                return db;
            }
              try {
                String dbPath = Config.sharedInstance().value("db.path");
                String dbUsername =  Config.sharedInstance().value("db.username");
                String dbPassword =  Config.sharedInstance().value("db.password");

                int dbPort = Integer.parseInt( Config.sharedInstance().value("db.port"));
                String dbName =  Config.sharedInstance().value("db.name");
                MongoClient mongoClient = new MongoClient(dbPath, dbPort);
                    db=mongoClient.getDatabase(dbName);

            } catch (Throwable e) {

            }

            return db;
        }
    }

previously i was using 2.10 jar but now using the latest version i found that db.getDB() is a deprecated method and i found getDatabase() method instead. So now i want to authenticate the DB with username and password. but i didn't find out db.auth() method. Please help.

Community
  • 1
  • 1
Kamini
  • 690
  • 2
  • 13
  • 36
  • this will help you: https://docs.mongodb.org/getting-started/java/client/ – Dev Nov 19 '15 at 07:13
  • a lot of things has changed in 3.0 version. this answer may help: http://stackoverflow.com/a/31109322/3929393 – Dev Nov 19 '15 at 07:16

1 Answers1

1

You can create MongoClientURI with mongodb connection string with authentication information and pass this MongoClientURI to MongoClient constructer.

MongoClientURI uri = new MongoClientURI("mongodb://userId:password@hostName:port/dbName");
MongoClient mongoClient = new MongoClient(uri);
MongoDatabase db = mongoClient.getDatabase("yourdatabasename");
MongoCollection<Document> collection = db.getCollection("yourcollection");

Refer MongoDB java driver API for more information:

António Ribeiro
  • 4,129
  • 5
  • 32
  • 49
  • which DB object should i use DB (com.mongodb.DB) or MongoDatabase(com.mongodb.client.MongoDatabase) , wherein if i write DB then i need to cast the object with DB object like this db=(DB) mongoClient.getDatabase(dbName); – Kamini Nov 19 '15 at 05:38
  • Updated my answer , you can use MongoDatabase object , from there you can get MongoCollection. – Balaji Thummalapenta Nov 19 '15 at 14:43