English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

MongoDB Java

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

Installation

Before starting to use MongoDB in Java programs, it is necessary to ensure that MongoDB CLIENT and Java are set up on the computer. You can install Java by following the Java tutorial on the computer. Now, let's check how to set up the MongoDB CLIENT.

  • You need to download jar mongodb-driver-3.11.2.jar and its dependency mongodb-driver-core-3.11.2.jar.. Make sure to download the latest versions of these jar files.

  • You need to include the downloaded jar file in the classpath.

Connect to the database

To connect to the database, you need to specify the database name. If the database does not exist, MongoDB will automatically create it.

The following is a code snippet for connecting to the database-

import com.mongodb.client.MongoDatabase; 
import com.mongodb.MongoClient; 
import com.mongodb.MongoCredential;  
public class ConnectToDB { 
   
   public static void main(String args[]) {  
      
      // Create a MongoDB client 
      MongoClient mongo = new MongoClient("localhost", 27017 ); 
   
      // Create credentials 
      MongoCredential credential; 
      credential = MongoCredential.createCredential("sampleUser", "myDb", 
         "password".toCharArray()); 
      System.out.println("Successfully connected to the database");  
      
      // Access Database 
      MongoDatabase database = mongo.getDatabase("myDb"); 
      System.out.println("Credentials ::"+ credential);     
   } 
}

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

$javac ConnectToDB.java $java ConnectToDB

After execution, the above program will provide you with the following output.

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

Create collection

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

The following is a code snippet for creating a collection-

import com.mongodb.client.MongoDatabase; 
import com.mongodb.MongoClient; 
import com.mongodb.MongoCredential;  
public class CreatingCollection { 
   
   public static void main(String args[]) {  
      
      // Create a MongoDB client 
      MongoClient mongo = new MongoClient("localhost", 27017 ); 
     
      // Create credentials 
      MongoCredential credential; 
      credential = MongoCredential.createCredential("sampleUser", "myDb", 
         "password".toCharArray()); 
      System.out.println("Successfully connected to the database");  
      
      //Access Database 
      MongoDatabase database = mongo.getDatabase("myDb");  
      
      //Create collection 
      database.createCollection("sampleCollection"); 
      System.out.println("Successfully created collection"); 
   } 
}

The above program provides the following results when compiled-

Successfully connected to the database, successfully created the collection

Obtain/Select collection

To retrieve from the database/To select a collection, you need to use the getCollection() method of the com.mongodb.client.MongoDatabase class.

The following is to obtain/Program to select 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[]) {  
      
      // Create a MongoDB client 
      MongoClient mongo = new MongoClient("localhost", 27017 ); 
     
      // Create credentials 
      MongoCredential credential; 
      credential = MongoCredential.createCredential("sampleUser", "myDb", 
         "password".toCharArray()); 
      System.out.println("Successfully connected to the database");  
      
      // Access Database 
      MongoDatabase database = mongo.getDatabase("myDb");  
      
      // Create collection
      System.out.println("Successfully created collection"); 
      // Retrieve collection
      MongoCollection<Document> collection = database.getCollection("myCollection"); 
      System.out.println("Successfully selected collection myCollection"); 
   }
}

The above program provides the following results when compiled-

Successfully connected to the database, successfully created the collection, successfully selected collection myCollection

Insert document

To insert a document into MongoDB, you need to use the insert() method of the com.MongoDB.client.MongoCollection class.

The following is the code snippet for inserting 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[]) {
	// Create a MongoDB client
	MongoClient mongo = new MongoClient("localhost", 27017 );
	// Access Database
	MongoDatabase database = mongo.getDatabase("myDb");
	// Create collection
	database.createCollection("sampleCollection");
	System.out.println("Successfully created collection");
	// Retrieve collection
	MongoCollection<Document> collection = database.getCollection("sampleCollection");
	System.out.println("Successfully selected collection sampleCollection");
	Document document = new Document("title", "MongoDB")
	.append("description", "database")
	.append("likes", 100)
	.append("url", "http://www.oldtoolbag.com/mongodb/")
	.append("by", "oldtoolbag.com");
	//Insert the document into the collection
	collection.insertOne(document);
	System.out.println("Document inserted successfully");
}

The above program provides the following results when compiled-

Successfully connected to the database Successfully selected collection sampleCollection Document inserted successfully

Retrieve all documents

To select all documents from the collection, please usecom.mongodb.client.MongoCollection of the classfind()Method. This method returns a cursor, so you need to iterate over this cursor.

The following is the program to select 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[]) {
		// Create a MongoDB client
		MongoClient mongo = new MongoClient("localhost", 27017 );
		// Create credentials
		MongoCredential credential;
		credential = MongoCredential.createCredential("sampleUser", "myDb", "password".toCharArray());
		System.out.println("Successfully connected to the database");
		// Access Database
		MongoDatabase database = mongo.getDatabase("myDb");
		// Retrieve collection
		MongoCollection<Document> collection = database.getCollection("sampleCollection");
		System.out.println("Successfully selected collection sampleCollection");
		Document document1 = new Document("title", "MongoDB")
		.append("description", "database")
		.append("likes", 100)
		.append("url", "http://www.oldtoolbag.com/mongodb/")
		.append("by", "oldtoolbag.com");
		Document document2 = new Document("title", "RethinkDB")
		.append("description", "database")
		.append("likes", 200)
		.append("url", "http://www.oldtoolbag.com/rethinkdb/")
		.append("by", "oldtoolbag.com");
		List<Document> list = new ArrayList<Document>();
		list.add(document1);
		list.add(document2);
		collection.insertMany(list);
		// Get iterable object
		FindIterable<Document> iterDoc = collection.find();
		int i = 1;
		// Get iterator
		Iterator it = iterDoc.iterator();
		while (it.hasNext()) {
			System.out.println(it.next());
			i++;
		}
	}
}

The above program provides the following results when compiled-

Successfully connected to the database Successfully selected collection sampleCollection{{_id=5dce4e9ff68a9c2449e197b2, title=MongoDB, description=database, likes=100, url=http://www.oldtoolbag.com/mongodb/, by=oldtoolbag.com}}Document{{_id=5dce4e9ff68a9c2449e197b3, title=RethinkDB, description=database, likes=200, url=http://www.oldtoolbag.com/rethinkdb/, by=oldtoolbag.com}}

Update document

To update a document in the collection, please useThe class of com.mongodb.client.MongoCollectionupdateOne()Method.

The following is the program for selecting 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[]) {  
      
      // Create a MongoDB client 
      MongoClient mongo = new MongoClient("localhost", 27017 ); 
     
      // Create credentials 
      MongoCredential credential; 
      credential = MongoCredential.createCredential("sampleUser", "myDb", 
         "password".toCharArray()); 
      System.out.println("Successfully connected to the database");  
      
      // Access Database 
      MongoDatabase database = mongo.getDatabase("myDb"); 
      // Retrieve collection 
      MongoCollection<Document> collection = database.getCollection("sampleCollection");
      System.out.println("Successfully selected collection myCollection"); 
      collection.updateOne(Filters.eq("title", 1), Updates.set("likes", 150));       
      System.out.println("Document update successful...");  
      
      // Retrieve document after update 
      // Get iterable object
      FindIterable<Document> iterDoc = collection.find(); 
      int i = 1; 
      // Get iterator 
      Iterator it = iterDoc.iterator(); 
      while (it.hasNext()) {  
         System.out.println(it.next());  
         i++; 
      }     
   }  
}

The above program provides the following results when compiled-

Successfully connected to the database Successfully selected collection myCollection Document update successful...Document{{_id=5dce4e9ff68a9c2449e197b2, title=MongoDB, description=database, likes=100, url=http://www.oldtoolbag.com/mongodb/, by=oldtoolbag.com}}Document{{_id=5dce4e9ff68a9c2449e197b3, title=RethinkDB, description=database, likes=200, url=http://www.oldtoolbag.com/rethinkdb/, by=oldtoolbag.com}}

Delete document

To delete a document from the collection, you need to use the classcom.mongodb.client.MongoCollectionofdeleteOne()Method.

The following is the program for deleting documents-

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[]) {  
   
      // Create a MongoDB client 
      MongoClient mongo = new MongoClient("localhost", 27017 );
      
      // Create credentials 
      MongoCredential credential; 
      credential = MongoCredential.createCredential("sampleUser", "myDb", 
         "password".toCharArray()); 
      System.out.println("Successfully connected to the database");  
      
      // Access Database 
      MongoDatabase database = mongo.getDatabase("myDb"); 
      // Retrieve collection
      MongoCollection<Document> collection = database.getCollection("sampleCollection");
      System.out.println("Successfully selected collection sampleCollection"); 
      // Delete file 
      collection.deleteOne(Filters.eq("title", "MongoDB")); 
      System.out.println("Document deletion successful...");  
      
      // Retrieve document after update 
      // Get iterable object 
      FindIterable<Document> iterDoc = collection.find(); 
      int i = 1; 
      // Get iterator 
      Iterator it = iterDoc.iterator(); 
      while (it.hasNext()) {  
         System.out.println(it.next());  
         i++; 
      }       
   } 
}

The above program provides the following results when compiled-

Successfully connected to the database Successfully selected collection sampleCollection Document deletion successful...5dce4e9ff68a9c2449e197b3, title=RethinkDB, description=database, likes=200, url=http://www.oldtoolbag.com/rethinkdb/, by=oldtoolbag.com}}

Delete collection

To delete a collection from the database, you need to use the classcom.mongodb.client.MongoCollectionofdrop()Method.

The following program is for deleting 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 DropingCollection { 
   
   public static void main(String args[]) {  
      // Create a MongoDB client 
      MongoClient mongo = new MongoClient("localhost", 27017 ); 
      // Create credentials 
      MongoCredential credential; 
      credential = MongoCredential.createCredential("sampleUser", "myDb", 
         "password".toCharArray()); 
      System.out.println("Successfully connected to the database");  
      
      // Access Database 
      MongoDatabase database = mongo.getDatabase("myDb");  
      
      // Create collection
      System.out.println("Successfully created collection"); 
      // Retrieve collection
      MongoCollection<Document> collection = database.getCollection("sampleCollection");
      // Delete collection 
      collection.drop(); 
      System.out.println("Successfully deleted collection");
   } 
}

The above program provides the following results when compiled-

Successfully connected to database Collection sampleCollection selected successfully Successfully deleted collection

List all collections

To list all collections in the database, you need to use the classThe method of com.mongodb.client.MongoDatabaselistCollectionNames()Method.

The following program lists all collections in the database-

import com.mongodb.client.MongoDatabase; 
import com.mongodb.MongoClient; 
import com.mongodb.MongoCredential;  
public class ListOfCollection { 
   
   public static void main(String args[]) {  
      
      // Create a MongoDB client 
      MongoClient mongo = new MongoClient("localhost", 27017 ); 
      // Create credentials 
      MongoCredential credential; 
      credential = MongoCredential.createCredential("sampleUser", "myDb", 
         "password".toCharArray()); 
      System.out.println("Successfully connected to the database");  
      
      // Access Database 
      MongoDatabase database = mongo.getDatabase("myDb"); 
      System.out.println("Successfully created collection"); 
      for (String name : database.listCollectionNames()) { 
         System.out.println(name); 
      } 
   }
}

The above program provides the following results when compiled-

Successfully connected to the database Successfully created collection myCollection myCollection1 myCollection5

The rest of the MongoDB methods save ()、 limit ()、 skip ()、 sort () and others work in the same way as explained in the subsequent tutorials.