简体   繁体   中英

MongoDb database connection using java and authentication with 3.0.0 version

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.

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM