English 中文(简体)
Java & MongoDB - Connect Database
  • 时间:2024-12-22

Java & MongoDB - Connecting Database


Previous Page Next Page  

To connect database, you need to specify the database name, if the database doesn t exist then MongoDB creates it automatically.


MongoDatabase database = mongo.getDatabase("myDb");

Example

Following is the code snippet to connect to the database −


import com.mongodb.MongoCredential;
import com.mongodb.cpent.MongoCpent;
import com.mongodb.cpent.MongoCpents;
import com.mongodb.cpent.MongoDatabase;

pubpc class Tester {
   pubpc static void main(String[] args) {
      // Creating a Mongo cpent 
      MongoCpent mongoCpent = MongoCpents.create("mongodb://localhost:27017");
      MongoDatabase database = mongo.getDatabase("myDb");

      // Creating Credentials 
      MongoCredential credential; 
      credential = MongoCredential.createCredential("sampleUser", "myDb", "password".toCharArray());

      System.out.println("Credentials ::"+ credential);  
   }
}

Now, let s compile and run the above program as shown below.


$javac Tester.java 
$java Tester

Output

On executing, the above program gives you the following output.


Credentials ::MongoCredential{mechanism=null, userName= sampleUser , source= myDb , password=<hidden>, mechanismProperties=<hidden>}
Advertisements