MongoDB - Java

MongoDB - PHP

MongoDB - Advanced

MongoDB - Useful Resources

MongoDB - Java Setup



In this chapter, we will learn how to set up MongoDB CLIENT.

Installation

Before you start using MongoDB in your Java programs, you need to make sure that you have MongoDB CLIENT and Java set up on the machine. You can check Java - Environment Setup for Java installation on your machine. Now, let us check how to set up MongoDB CLIENT.

We're using Maven based Java Project to install MongoDB driver dependencies.

Add MongoDB Driver BOM to pom.xml

Add MongoDB driver BOM dependency under dependencyManagement list. BOM manages versions of mongodb driver and other dependencies.

<dependencyManagement>
...
   <dependencies>
      <dependency>
         <groupId>org.mongodb</groupId>
         <artifactId>mongodb-driver-bom</artifactId>
         <version>5.6.2</version>
         <type>pom</type>
         <scope>import</scope>
      </dependency>
   </dependencies>
</dependencyManagement>

Add MongoDB Java Driver to pom.xml

<dependencies>
...
   <dependency>
      <groupId>org.mongodb</groupId>
      <artifactId>mongodb-driver-sync</artifactId>
   </dependency>
</dependencies>

Connect to Database

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

Following is the code snippet to connect to the database −

package com.tutorialspoint.mongodb;

import com.mongodb.MongoCredential;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoDatabase;  

public class MongoDBTester { 
   
   public static void main( String args[] ) { 
      String uri = "mongodb://localhost:27017/";    
      try (MongoClient mongoClient = MongoClients.create(uri)) {
         MongoDatabase database = mongoClient.getDatabase("myDb");
         System.out.println("Connected to the database successfully");
         // Creating Credentials 
         MongoCredential credential; 
         credential = MongoCredential.createCredential("sampleUser", "myDb", 
            "password".toCharArray()); 
         System.out.println("Credentials ::"+ credential);  
      }
   } 
}

Output

Now, let's compile and run the above program to create our database myDb.

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

Connected to the database successfully
Credentials ::MongoCredential{mechanism=null, userName='sampleUser', source='myDb', password=<hidden>, mechanismProperties=<hidden>}
Advertisements