Home >>MongoDB Tutorial >MongoDB Java

MongoDB Java

MongoDB Java Setup

Installation

You need to make sure you have MongoDB CLIENT and Java set up on the system before you start using MongoDB on your Java programs. You should check your machine's Java installation tutorial for Java. Now, let's check how the MongoDB CLIENT should be set up.

  • You need to download the jar mongodb-driver-3.11.2.jar and its dependency mongodb-driver-core-3.11.2.jar.. Make sure to download the latest release of these jar files.
  • You need to include the downloaded jar files into your classpath.

Connect to Database

You need to define the database name to link the database, if the database does not exist then MongoDB will create it automatically.

The following is the code snippet for the database connect.

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("sampleUser", "myDb", 
         "password".toCharArray()); 
      System.out.println("Connected to the database successfully");  
      
      // Accessing the database 
      MongoDatabase database = mongo.getDatabase("myDb"); 
      System.out.println("Credentials ::"+ credential);     
   } 
}

Now, let's compile and run the above software, as shown below, to build our myDb database.

$javac ConnectToDB.java 
$java ConnectToDB
Output:

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 = {}
}

Create a Collection

To create a collection, createCollection() method of com.mongodb.client.MongoDatabase class is used.

Following is the code snippet to create a collection −

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("sampleUser", "myDb", 
         "password".toCharArray()); 
      System.out.println("Connected to the database successfully");  
      
      //Accessing the database 
      MongoDatabase database = mongo.getDatabase("myDb");  
      
      //Creating a collection 
      database.createCollection("sampleCollection"); 
      System.out.println("Collection created successfully"); 
   } 
} 
Output:

On compiling, the above program gives you the following result −

Connected to the database successfully 
Collection created successfully

Getting/Selecting a Collection

The getCollection() method from the com.mongodb.client. MongoDatabase class is used to get / select a collection from the database.

The program to get / select a collection follows.

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("sampleUser", "myDb", 
         "password".toCharArray()); 
      System.out.println("Connected to the database successfully");  
      
      // Accessing the database 
      MongoDatabase database = mongo.getDatabase("myDb");  
      
      // Creating a collection 
      System.out.println("Collection created successfully"); 
      // Retrieving a collection
      MongoCollection <Document> collection = database.getCollection("myCollection"); 
      System.out.println("Collection myCollection selected successfully"); 
   }
}
Output:

On compiling, the above program gives you the following result −

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

Insert a Document

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

Following is the code snippet to insert a document −

import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import com.mongodb.MongoClient;
public class InsertingDocument {
	public static void main( String args[] ) {
	
	// Creating a Mongo client
	MongoClient mongo = new MongoClient( "localhost" , 27017 );
	
	// Accessing the database
	MongoDatabase database = mongo.getDatabase("myDb");
	
	// Creating a collection
	database.createCollection("sampleCollection");
	System.out.println("Collection created successfully");
	
	// Retrieving a collection
	MongoCollection <Document> collection = database.getCollection("sampleCollection");
	System.out.println("Collection sampleCollection selected successfully");
	Document document = new Document("title", "MongoDB")
	.append("description", "database")
	.append("likes", 100)
	.append("url", "http://www.phptpoint.com/mongodb/")
	.append("by", "phptpoint");
	
	//Inserting document into the collection
	collection.insertOne(document);
	System.out.println("Document inserted successfully");
}
Output:

On compiling, the above program gives you the following result −

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

Retrieve All Documents

The find() method is used by the com.mongodb.client. MongoCollection class to select all documents from the collection. This method returns a cursor, so this is the cursor you need to iterate.

The following is the select program for all documents.

import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
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("sampleUser", "myDb", "password".toCharArray());
		System.out.println("Connected to the database successfully");
		
		// Accessing the database
		MongoDatabase database = mongo.getDatabase("myDb");
		
		// Retrieving a collection
		MongoCollection<Document> collection = database.getCollection("sampleCollection");
		System.out.println("Collection sampleCollection selected successfully");
		Document document1 = new Document("title", "MongoDB")
		.append("description", "database")
		.append("likes", 100)
		.append("url", "http://www.phptpoint.com/mongodb/")
		.append("by", "phptpoint");
		Document document2 = new Document("title", "RethinkDB")
		.append("description", "database")
		.append("likes", 200)
		.append("url", "http://www.phptpoint.com/rethinkdb/")
		.append("by", "phptpoint");
		List<Document> list = new ArrayList<Document>();
		list.add(document1);
		list.add(document2);
		collection.insertMany(list);
		// 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++;
		}
	}
}
Output:

On compiling, the above program gives you the following result −

Connected to the database successfully
Collection sampleCollection selected successfully
Document{{_id=5dce4e9ff68a9c2449e197b2, title=MongoDB, description=database, likes=100, url=http://www.phptpoint.com/mongodb/, by=phptpoint}}
Document{{_id=5dce4e9ff68a9c2449e197b3, title=RethinkDB, description=database, likes=200, url=http://www.phptpoint.com/rethinkdb/, by=phptpoint}}

Update Document

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

Following is the program to select the first document −

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("sampleUser", "myDb", 
         "password".toCharArray()); 
      System.out.println("Connected to the database successfully");  
      
      // Accessing the database 
      MongoDatabase database = mongo.getDatabase("myDb"); 
      // Retrieving a collection 
      MongoCollection<Document> collection = database.getCollection("sampleCollection");
      System.out.println("Collection myCollection selected successfully"); 
      collection.updateOne(Filters.eq("title", 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++; 
      }     
   }  
}
Output:

On compiling, the above program gives you the following result −

Connected to the database successfully
Collection myCollection selected successfully
Document update successfully...
Document{{_id=5dce4e9ff68a9c2449e197b2, title=MongoDB, description=database, likes=100, url=http://www.phptpoint.com/mongodb/, by=phptpoint}}
Document{{_id=5dce4e9ff68a9c2449e197b3, title=RethinkDB, description=database, likes=200, url=http://www.phptpoint.com/rethinkdb/, by=phptpoint}}

Delete a Document

You need to use the deleteOne() method in the com.mongodb.client. MongoCollection class to delete a document from the set.

The program to delete a document is followed.

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("sampleUser", "myDb", 
         "password".toCharArray()); 
      System.out.println("Connected to the database successfully");  
      
      // Accessing the database 
      MongoDatabase database = mongo.getDatabase("myDb"); 
      // Retrieving a collection
      MongoCollection<Document> collection = database.getCollection("sampleCollection");
      System.out.println("Collection sampleCollection selected successfully"); 
      // Deleting the documents 
      collection.deleteOne(Filters.eq("title", "MongoDB")); 
      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(it.next());  
         i++; 
      }       
   } 
}
Output:

On compiling, the above program gives you the following result −

Connected to the database successfully 
Collection sampleCollection selected successfully 
Document deleted successfully...
Document{{_id=5dce4e9ff68a9c2449e197b3, title=RethinkDB, description=database, likes=200, url=http://www.phptpoint.com/rethinkdb/, by= phptpoint }}

Dropping a Collection

You need to use the drop() method in the com.mongodb.client. MongoCollection class to drop a collection from a database.

The programme to delete a collection is accompanied by

import com.mongodb.client.MongoCollection; 
import com.mongodb.client.MongoDatabase;  
import org.bson.Document;  
import com.mongodb.MongoClient; 
import com.mongodb.MongoCredential;  
public class DropingCollection { 
   
   public static void main( String args[] ) {  
      // Creating a Mongo client 
      MongoClient mongo = new MongoClient( "localhost" , 27017 ); 
      // Creating Credentials 
      MongoCredential credential; 
      credential = MongoCredential.createCredential("sampleUser", "myDb", 
         "password".toCharArray()); 
      System.out.println("Connected to the database successfully");  
      
      // Accessing the database 
      MongoDatabase database = mongo.getDatabase("myDb");  
      
      // Creating a collection 
      System.out.println("Collections created successfully"); 
      // Retrieving a collection
      MongoCollection<Document> collection = database.getCollection("sampleCollection");
      // Dropping a Collection 
      collection.drop(); 
      System.out.println("Collection dropped successfully");
   } 
}
Output:

On compiling, the above program gives you the following result −

Connected to the database successfully 
Collection sampleCollection selected successfully 
Collection dropped successfully

Listing All the Collections

You need to use the listCollectionNames() method in the com.mongodb.client. MongoDatabase class to list all collections in a database.

The following is the programme to list all database collections −

import com.mongodb.client.MongoDatabase; 
import com.mongodb.MongoClient; 
import com.mongodb.MongoCredential;  
public class ListOfCollection { 
   
   public static void main( String args[] ) {  
      
      // Creating a Mongo client 
      MongoClient mongo = new MongoClient( "localhost" , 27017 ); 
      // Creating Credentials 
      MongoCredential credential; 
      credential = MongoCredential.createCredential("sampleUser", "myDb", 
         "password".toCharArray()); 
      System.out.println("Connected to the database successfully");  
      
      // Accessing the database 
      MongoDatabase database = mongo.getDatabase("myDb"); 
      System.out.println("Collection created successfully"); 
      for (String name : database.listCollectionNames()) { 
         System.out.println(name); 
      } 
   }
} 
Output:

On compiling, the above program gives you the following result −

Connected to the database successfully 
Collection created successfully 
myCollection 
myCollection1 
myCollection5

Remaining MongoDB methods save(), limit(), skip(), sort() etc. work same as explained in the subsequent tutorial.


No Sidebar ads