How to Execute MongoDB in Java Program – MongoDB Java

FREE Online Courses: Knowledge Awaits – Click for Free Access!

Since we have studied MongoDB Relationships & Database Reference. Here, in this MongoDB Java Tutorial, we are going to learn how to execute MongoDB in Java Program. Here, we will discuss how to connect, create, select, insert, retrieve, delete, and update documents and connections in MongoDB.

So, are you ready to execute MongoDB in Java Program?

How to Execute MongoDB in Java Program?

Before we start executing MongoDB in Java programs, we need to make sure that we are having MongoDB JDBC driver and Java set up on our machines. Make sure you have downloaded the latest MongoDB JDBC driver. Here, we will learn:

  1. Connect Database
  2. Create Connection
  3. Select a Connection
  4. Insert a Document
  5. Retrieve all document
  6. Delete Document
  7. Update Document

i. How to Connect to Mongo Database in Java Program?

For connecting to a database you need to specify the name of a database, if the database does not exist then MongoDB will create it automatically.

Following is the code for that:

import com.mongodb.client.MongoDatabase; 
import com.mongodb.MongoClient; 
import com.mongodb.MongoCredential;
public class ConnectToDB { 
  public static void main( String args[] ) { 
     // Creating a Mongo client 
     MongoClient mongo = new MongoClient( "localhost" , 27017 ); 
     // Creating Credentials 
     MongoCredential credential; 
credential = MongoCredential.createCredential("examplesUser", "examplesDb", 
"password".toCharArray()); 
System.out.println("Connected to the database successfully"); 
     // Accessing the database 
     MongoDatabase database = mongo.getDatabase("examplesDb"); 
     System.out.println("Credentials ::"+ credential); 
    } 
 }

Now to compile and execute this program you will have to type the following command by which exampleDb database will be created.

$javac ConnectToDB.java 
$java ConnectToDB

The output for the following code will be as follows:

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

ii. How to Create a MongoDB Collection in Java?

For creating a collection, we will use createCollection() method of com.mongodb.client.MongoDatabase class.

The code for this command is as follows:

import com.mongodb.client.MongoDatabase; 
import com.mongodb.MongoClient; 
import com.mongodb.MongoCredential;
public class CreatingCollection { 
  public static void main( String args[] ) { 
     // Creating a Mongo client 
     MongoClient mongo = new MongoClient( "localhost" , 27017 ); 
     // Creating Credentials 
     MongoCredential credential; 
     credential = MongoCredential.createCredential("examplesUser",                "examplesDb", 
       "password".toCharArray()); 
     System.out.println("Connected to the database successfully"); 
     //Accessing the database 
     MongoDatabase database = mongo.getDatabase("myDb"); 
     //Creating a collection 
     database.createCollection("examplesCollection"); 
     System.out.println("Collection created successfully"); 
   } 
 }

After executing this code we will get the following output:

Connected to the database successfullyA collection created successfully

iii. How to Select a MongoDB Collection in Java?

getCollection() method of com.mongodb.client.MongoDatabase class is used to select a collection from MongoDB.

Following is the code for selecting a collection:

import com.mongodb.client.MongoCollection; 
import com.mongodb.client.MongoDatabase;
import org.bson.Document; 
import com.mongodb.MongoClient; 
import com.mongodb.MongoCredential;
public class selectingCollection { 
  public static void main( String args[] ) {  
      // Creating a Mongo client 
      MongoClient mongo = new MongoClient( "localhost" , 27017 ); 
      // Creating Credentials 
      MongoCredential credential; 
      credential = MongoCredential.createCredential("examplesUser", "examplesDb", 
      "password".toCharArray()); 
      System.out.println("Connected to the database successfully"); 
      // Accessing the database 
      MongoDatabase database = mongo.getDatabase("examplesDb"); 
      // Creating a collection 
      System.out.println("Collection created successfully");
      // Retieving a collection
      MongoCollection<Document> collection =       database.getCollection("examplesCollection"); 
      System.out.println("Collection examplesCollection selected successfully"); 
      }
  }

On executing the above code you will get the following output as follows:

Connected to the database successfully
Collection created successfully
Collection myCollection selected successfully

iv. How to Insert a MongoDB Document in Java?

insert() method of com.mongodb.client.MongoCollection class is used to insert a document into MongoDB.

Following is the code to insert a document:

import com.mongodb.client.MongoCollection; 
import com.mongodb.client.MongoDatabase;
import org.bson.Document; 
import com.mongodb.MongoClient; 
import com.mongodb.MongoCredential;
public class InsertingDocument { 
  public static void main( String args[] ) { 
     // Creating a Mongo client 
     MongoClient mongo = new MongoClient( "localhost" , 27017 );
     // Creating Credentials 
     MongoCredential credential; 
     credential = MongoCredential.createCredential("examplesUser",      "examplesDb", 
     "password".toCharArray()); 
     System.out.println("Connected to the database successfully"); 
     // Accessing the database 
     MongoDatabase database = mongo.getDatabase("examplesDb");
     // Retrieving a collection
     MongoCollection<Document> collection =      database.getCollection("examplesCollection"); 
     System.out.println("Collection examplesCollection selected successfully");
     Document document = new Document("title", "MongoDB") 
     .append("id", 1)
     .append("description", "database") 
     .append("likes", 100) 
     .append("url", "http://www.data-flair.training/mongodb/") 
     .append("by", "data flair"); 
     collection.insertOne(document); 
     System.out.println("Document inserted successfully"); 
   } 
}

When you will run the following code, the output will be as follows:

Connected to the database successfully
Collection examplesCollection selected successfully
Document inserted successfully

v. How to Retrieve all documents in MongoDB Java?

find() method of com.mongodb.client.MongoCollection class is used to select all documents from the collection. It will return a cursor, so you need to iterate this cursor.

Following is the code to retrieve all documents:

import com.mongodb.client.FindIterable; 
import com.mongodb.client.MongoCollection; 
import com.mongodb.client.MongoDatabase;
import java.util.Iterator; 
import org.bson.Document; 
import com.mongodb.MongoClient; 
import com.mongodb.MongoCredential;
public class RetrievingAllDocuments { 
   public static void main( String args[] ) { 
   // Creating a Mongo client 
   MongoClient mongo = new MongoClient( "localhost" , 27017 );
   // Creating Credentials 
   MongoCredential credential;
   credential = MongoCredential.createCredential("examplesUser",    "examplesDb", 
   "password".toCharArray()); 
   System.out.println("Connected to the database successfully"); 
   // Accessing the database 
   MongoDatabase database = mongo.getDatabase("examplesDb"); 
   // Retrieving a collection 
   MongoCollection<Document> collection =    database.getCollection("examplesCollection");
   System.out.println("Collection examplesCollection selected successfully");
   // Getting the iterable object 
   FindIterable<Document> iterDoc = collection.find(); 
   int i = 1;
   // Getting the iterator 
   Iterator it = iterDoc.iterator(); 
   while (it.hasNext()) { 
   System.out.println(it.next()); 
   i++; 
   }
  } 
}

After executing the program you will get the following output:

Document{{
_id = 5967745223993a32646baab8,
title = MongoDB,
id = 1,
description = database,
likes = 100,
url = http://www.data-flair.training/mongodb/, by = data flair
}}
Document{{
_id = 7452239959673a32646baab8,
title = RethinkDB,
id = 2,
description = database,
likes = 200,
url = http://www.data-flair.training/rethinkdb/, by = data flair
}}

vi. How to Update Document in MongoDB Java?

updateOne() method of com.mongodb.client.MongoCollection class is used to update a document from the collection.

Following is the code to update a document from the collection:

import com.mongodb.client.FindIterable; 
import com.mongodb.client.MongoCollection; 
import com.mongodb.client.MongoDatabase; 
import com.mongodb.client.model.Filters; 
import com.mongodb.client.model.Updates;
import java.util.Iterator; 
import org.bson.Document; 
import com.mongodb.MongoClient; 
import com.mongodb.MongoCredential;
public class UpdatingDocuments { 
  public static void main( String args[] ) { 
      // Creating a Mongo client 
      MongoClient mongo = new MongoClient( "localhost" , 27017 ); 
      // Creating Credentials 
      MongoCredential credential; 
      credential = MongoCredential.createCredential("examplesUser", "examplesDb", 
      "password".toCharArray()); 
      System.out.println("Connected to the database successfully"); 
      // Accessing the database 
      MongoDatabase database = mongo.getDatabase("examplesDb");
      // Retrieving a collection 
      MongoCollection<Document> collection =             database.getCollection("examplesCollection");
      System.out.println("Collection examplesCollection selected successfully");
      collection.updateOne(Filters.eq("id", 1), Updates.set("likes", 150)); 
      System.out.println("Document update successfully..."); 
      // Retrieving the documents after updation 
      // Getting the iterable object
      FindIterable<Document> iterDoc = collection.find(); 
      int i = 1;
      // Getting the iterator 
      Iterator it = iterDoc.iterator();
      while (it.hasNext()) { 
      System.out.println(it.next()); 
      i++; 
     } 
   } 
}

When you execute the following code you will get this output:

Document update successfully…Document {{
_id = 5967745223993a32646baab8,
title = MongoDB,
id = 1,
description = database,
likes = 150,
url = http://www.data-flair.training/mongodb/, by = data flair
}}

vii. How to Delete a Document in MongoDB Java?

deleteOne() method of com.mongodb.client.MongoCollection class is used to delete a document from the collection.

Following is the code to delete a document from the collection:

import com.mongodb.client.FindIterable; 
import com.mongodb.client.MongoCollection; 
import com.mongodb.client.MongoDatabase; 
import com.mongodb.client.model.Filters;
import java.util.Iterator; 
import org.bson.Document; 
import com.mongodb.MongoClient; 
import com.mongodb.MongoCredential;
public class DeletingDocuments { 
  public static void main( String args[] ) { 
     // Creating a Mongo client 
      MongoClient mongo = new MongoClient( "localhost" , 27017 );
      // Creating Credentials 
      MongoCredential credential; 
      credential = MongoCredential.createCredential("examplesUser", "examplesDb", 
      "password".toCharArray()); 
      System.out.println("Connected to the database successfully");
      // Accessing the database 
      MongoDatabase database = mongo.getDatabase("examplesDb");
      // Retrieving a collection
      MongoCollection<Document> collection =       database.getCollection("examplesCollection");
      System.out.println("Collection examplesCollection selected successfully");
      // Deleting the documents 
      collection.deleteOne(Filters.eq("id", 1)); 
      System.out.println("Document deleted successfully..."); 
      // Retrieving the documents after updation 
      // Getting the iterable object 
      FindIterable<Document> iterDoc = collection.find(); 
      int i = 1;
      // Getting the iterator 
      Iterator it = iterDoc.iterator();
      while (it.hasNext()) { 
      System.out.println("Inserted Document: "+i); 
      System.out.println(it.next()); 
      i++; 
     } 
   } 
}

After executing the program you will get the following output:

Connected to the database successfully
Collection examplesCollection selected successfully
Document deleted successfully…

Summary

Hence, we have discussed the execution of MongoDB in Java program with the help of MongoDB JDBC driver. Moreover, we learned insert, create, update, delete the documents and connections in MongoDB in Java programs.

Still, have a doubt? Feel free to ask in the comment tab.

Your 15 seconds will encourage us to work even harder
Please share your happy experience on Google

follow dataflair on YouTube

3 Responses

  1. Azim Surani says:

    Please, can you make a tutorial with latest mongo java driver cause many of the classes have been removed in the latest version.

    • DataFlair Team says:

      Hi Azim,
      Thanks for commenting on MongoDB in Java Tutorial. We are glad our readers trying to interact with us. Surely we will work on your suggestion and publish the article soon.
      Stay with us!
      Regards,
      DataFlair

  2. ganesh athmagnanam says:

    Dear Team,
    I just wanted only records, i don’t want Document to be preceded by document tag like below
    Document{{
    _id = 5967745223993a32646baab8,
    title = MongoDB,
    id = 1,
    description = database,
    likes = 100,
    url = https://data-flair.training/blogs/mongodb-tutorials-home/, by = data flair
    }}
    Document{{
    _id = 7452239959673a32646baab8,
    title = RethinkDB,
    id = 2,
    description = database,
    likes = 200,
    url = https://data-flair.training/blogs/python-tutorials-home/, by = data flair
    }}

    any idea how to get rid of these

Leave a Reply

Your email address will not be published. Required fields are marked *