w3resource logo


Mongodb Tutorial Introduction

MongoDb : Java Driver

Secondary Nav

Introduction

MongoDB provides connectivity for Java client applications using Java driver. Using the Java driver is simple, just include the driver jar mongo.jar in your classpath. You will get more information about the Java API from here.

Download mongo.jar from here.

The JDBC API can do the following things :

  • Establish a connection with a database or access any tabular data source.
  • Send various MongoDB statements.
  • Retrieve and process the results received from the database.

Making a Connection

Here are some of the common methods to connect to a MongoDB server :

To directly connect to a single MongoDB server :

MongoClient mongoClient = new MongoClient();
// or
MongoClient mongoClient = new MongoClient( "localhost" );
// or
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );

To connect to a replica set, with auto-discovery of the primary, supply a seed list of members :

MongoClient mongoClient = new MongoClient(Arrays.asList(new ServerAddress("localhost", 27017),
                                      new ServerAddress("localhost", 27018),
                                      new ServerAddress("localhost", 27019)));

Authentication (Optional) :
MongoDB can be run in a secure mode where access to databases is controlled via authentication. When run in this mode, any client application must provide a list of credentials which will be used to authenticate against. In the Java driver, you simply provide the credentials when creating a MongoClient instance:

MongoCredential credential = MongoCredential.createMongoCRCredential(userName, database, password);
MongoClient mongoClient = new MongoClient(new ServerAddress(), Arrays.asList(credential)); 

Connection to MongoDB Database :

Following code show how to create the connection to the MongoDB database. If the database is not present, MongoDB will create it for you.

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import java.util.List;
import java.util.Set;
import static java.util.concurrent.TimeUnit.SECONDS;

public class mongodb_connection{
   public static void main( String args[] ){
      try{   
		MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
		System.out.println("Database Connection Successful!");
        DB db = mongoClient.getDB( "testdb" );
	    }catch(Exception e){
	     System.err.println( e.getClass().getName() + ": " + e.getMessage() );
	  }
   }
}

Output :

F:\java-mongodb>javac mongodb_connection.java
F:\java-mongodb>java mongodb_connection
Database Connection Successful!

Insert a document

Once you have the collection object, you can insert documents into the collection. For example, let's create a student document that in JSON would be represented as :

{ 
  "name"   : "Arun",
  "class"  : 'V',
  "rollno" : 1
}  

Here we have used the BasicDBObject class to create the document, and then just simply insert it into the collection using the insert() method.

Code :

import com.mongodb.MongoClient;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBCursor;
import com.mongodb.ServerAddress;
import java.util.Arrays;

public class mongodb_connection_insert{
   public static void main( String args[] ){
      try{   
		MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
		DB db = mongoClient.getDB( "testdb" );
		System.out.println("Database Connection Successful!");
		DBCollection collec = db.getCollection("stucollec");
        BasicDBObject doc = new BasicDBObject("student", "testdb")
        .append("name", "Arun")
        .append("class", 'V')
		.append("rollno", 1);
collec.insert(doc);
 System.out.println("Document is inserted successfully");
	    }catch(Exception e){
	     System.err.println( e.getClass().getName() + ": " + e.getMessage() );
	  }
   }
}
         

Output :

F:\java-mongodb>java mongodb_connection_insert
Database Connection Successful!
Document is inserted successfully

Find a document

To show or find a document is simple, use findOne() operation to get the first document in the collection. This method returns a single document, and it's useful for things where there only is one document, or you are only interested in the first.

Code :

import com.mongodb.MongoClient;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBCursor;
import com.mongodb.ServerAddress;
import java.util.Arrays;

public class mongodb_connection_find_document{
   public static void main( String args[] ){
      try{   
		MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
		DB db = mongoClient.getDB( "testdb" );
		System.out.println("Database Connection Successful!");
		DBCollection collec = db.getCollection("stucollec");
    	DBObject myDoc = collec.findOne();
        System.out.println(myDoc);
        }catch(Exception e){
	     System.err.println( e.getClass().getName() + ": " + e.getMessage() );
	  }
   }
}  

Output :

F:\java-mongodb>java mongodb_connection_find_document
Database Connection Successful!
{ "_id" : { "$oid" : "54897b3309b478e666780749"} , "student" : "testdb" , "name" : "Arun" , "class" : "V" , "rollno" : 1}

Let insert two more records :

{ 
  "name"   : "David",
  "class"  : 'V',
  "rollno" : 2
}  
{ 
  "name"   : "Shekhar",
  "class"  : 'V',
  "rollno" : 3
}  

Using a Cursor to retrieve all documents

To get all the documents in the collection, we have used the find() method. The find() method returns a DBCursor object which allows us to iterate over the set of documents that matched our query. So to query all of the documents and print them out :

Code :

import com.mongodb.MongoClient;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBCursor;
import com.mongodb.ServerAddress;
import java.util.Arrays;

public class mongodb_connection_find_all_documents{
   public static void main( String args[] ){
      try{   
		MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
		DB db = mongoClient.getDB( "testdb" );
		DBCollection collec = db.getCollection("stucollec");
		DBCursor cursor = collec.find();
        try {
          while(cursor.hasNext()) {
          System.out.println(cursor.next());
         }
         } finally {
           cursor.close();
             }
        }catch(Exception e){
	     System.err.println( e.getClass().getName() + ": " + e.getMessage() );
	  }
   }
}
 

Output :

F:\java-mongodb>javac mongodb_connection_find_all_documents.java

F:\java-mongodb>java mongodb_connection_find_all_documents
{ "_id" : { "$oid" : "54897b3309b478e666780749"} , "student" : "testdb" , "name" : "Arun" , "class" : "V" , "rollno" : 1}
{ "_id" : { "$oid" : "5489890c09b4351818c6e73f"} , "student" : "testdb" , "name" : "David" , "class" : "V" , "rollno" : 2}
{ "_id" : { "$oid" : "54898b4309b45fce267b9fbe"} , "student" : "testdb" , "name" : "Shekhar" , "class" : "V" , "rollno" : 3}
             

A single document Query

We can create a query to pass to the find() method to get a subset of the documents in our collection. For example, if we wanted to find the document for which the value of the "rollno" field is 2, we would do the following ;

Code :

import com.mongodb.MongoClient;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBCursor;
import com.mongodb.ServerAddress;
import java.util.Arrays;

public class mongodb_connection_single_document_query{
   public static void main( String args[] ){
      try{   
		MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
		DB db = mongoClient.getDB( "testdb" );
		DBCollection collec = db.getCollection("stucollec");
		BasicDBObject query = new BasicDBObject("rollno", 2);
		DBCursor cursor = collec.find();
        cursor = collec.find(query);
         try {
          while(cursor.hasNext()) {
          System.out.println(cursor.next());
          }
            } finally {
         cursor.close();
        }
        }catch(Exception e){
	     System.err.println( e.getClass().getName() + ": " + e.getMessage() );
	  }
   }
}
 

Output :

F:\java-mongodb>javac mongodb_connection_single_document_query.java

F:\java-mongodb>java mongodb_connection_single_document_query
{ "_id" : { "$oid" : "5489890c09b4351818c6e73f"} , "student" : "testdb" , "name" : "David" , "class" : "V" , "rollno" : 2}
             

Multiple documents Query

We can use the query to get a set of documents from our collection. For example, if you want to get all documents where "rollno" >= 2, we can write :

Code :

import com.mongodb.MongoClient;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBCursor;
import com.mongodb.ServerAddress;
import java.util.Arrays;

public class mongodb_connection_multiple_documents_query{
   public static void main( String args[] ){
      try{   
		MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
		DB db = mongoClient.getDB( "testdb" );
		DBCollection collec = db.getCollection("stucollec");
		// find all where rollno>=2
        BasicDBObject  query = new BasicDBObject("rollno", new BasicDBObject("$gte", 2));
	    DBCursor cursor = collec.find(query);
try {
    while (cursor.hasNext()) {
        System.out.println(cursor.next());
    }
} finally {
    cursor.close();
}
        }catch(Exception e){
	     System.err.println( e.getClass().getName() + ": " + e.getMessage() );
	  }
   }
}
 

Output :

F:\java-mongodb>javac mongodb_connection_multiple_documents_query.java

F:\java-mongodb>java mongodb_connection_multiple_documents_query
{ "_id" : { "$oid" : "5489890c09b4351818c6e73f"} , "student" : "testdb" , "name" : "David" , "class" : "V" , "rollno" : 2}
{ "_id" : { "$oid" : "54898b4309b45fce267b9fbe"} , "student" : "testdb" , "name" : "Shekhar" , "class" : "V" , "rollno" : 3}
 

Update document

Following program shows how to use $set in java program to update a single matching document.

Code :

import com.mongodb.MongoClient;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBCursor;
import com.mongodb.ServerAddress;
import com.mongodb.WriteResult;
import java.util.Arrays;

public class mongodb_connection_update_document{
   public static void main( String args[] ){
      try{   
		MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
		DB db = mongoClient.getDB( "testdb" );
		DBCollection collec = db.getCollection("stucollec");
		
		DBObject query = new BasicDBObject("name", "Shekhar");
        DBObject update = new BasicDBObject();
        update.put("$set", new BasicDBObject("rollno", 13));
         
        WriteResult result = collec.update(query, update);
         
       	DBCursor cursor = collec.find();
        try {
          while(cursor.hasNext()) {
          System.out.println(cursor.next());
         }
         } finally {
           cursor.close();
             }
      }catch(Exception e){
	     System.err.println( e.getClass().getName() + ": " + e.getMessage() );
	  }
   }
}
             

Output :

F:\java-mongodb>javac mongodb_connection_update_document.java

F:\java-mongodb>java mongodb_connection_update_document
{ "_id" : { "$oid" : "54897b3309b478e666780749"} , "student" : "testdb" , "name" : "Arun" , "class" : "V" , "rollno" : 1}
{ "_id" : { "$oid" : "5489890c09b4351818c6e73f"} , "student" : "testdb" , "name" : "David" , "class" : "V" , "rollno" : 2}
{ "_id" : { "$oid" : "54898b4309b45fce267b9fbe"} , "student" : "testdb" , "name" : "Shekhar" , "class" : "V" , "rollno" : 13}

Delete a document

Following program shows how to delete a single matching document.

Code :

import com.mongodb.MongoClient;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBCursor;
import com.mongodb.ServerAddress;
import com.mongodb.WriteResult;
import java.util.Arrays;

public class mongodb_connection_delete_document{
   public static void main( String args[] ){
      try{   
		MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
		DB db = mongoClient.getDB( "testdb" );
		DBCollection collec = db.getCollection("stucollec");
		DBObject query = new BasicDBObject("rollno", 13);
        WriteResult result = collec.remove(query);
        System.out.println("Number of documents are deleted : " + result.getN());
		DBCursor cursor = collec.find();		
        try {
          while(cursor.hasNext()) {
          System.out.println(cursor.next());
         }
         } finally {
           cursor.close();
             }
      }catch(Exception e){
	     System.err.println( e.getClass().getName() + ": " + e.getMessage() );
	  }
   }
}

Output :

F:\java-mongodb>javac mongodb_connection_delete_document.java

F:\java-mongodb>java mongodb_connection_delete_document
Number of documents are deleted : 1
{ "_id" : { "$oid" : "54897b3309b478e666780749"} , "student" : "testdb" , "name" : "Arun" , "class" : "V" , "rollno" : 1}
{ "_id" : { "$oid" : "5489890c09b4351818c6e73f"} , "student" : "testdb" , "name" : "David" , "class" : "V" , "rollno" : 2}

List of collection

Following program returns a list of the available collections in a database :

Note : The system.indexes collection is automatically created and lists all the indexes in the database and shouldn’t be accessed directly.

Code :

import com.mongodb.MongoClient;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBCursor;
import com.mongodb.ServerAddress;
import com.mongodb.WriteResult;
import java.util.Arrays;

public class mongodb_connection_list_of_collection{
   public static void main( String args[] ){
      try{   
		MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
		DB db = mongoClient.getDB( "testdb" );
		for (String s : db.getCollectionNames()) {
        System.out.println(s);
		}
        }catch(Exception e){
	     System.err.println( e.getClass().getName() + ": " + e.getMessage() );
	  }
   }
}

Output :

F:\java-mongodb>javac mongodb_connection_list_of_collection.java

F:\java-mongodb>java mongodb_connection_list_of_collection
stucollec
system.indexes

Drop a collection

You can drop a collection by using the drop() method :

Code :

import com.mongodb.MongoClient;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBCursor;
import com.mongodb.ServerAddress;
import com.mongodb.WriteResult;
import java.util.Arrays;

public class mongodb_connection_drop_a_collection{
   public static void main( String args[] ){
      try{   
		MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
		DB db = mongoClient.getDB( "testdb" );
		DBCollection coll = db.getCollection("stucollec");
        coll.drop();
        System.out.println(db.getCollectionNames());
        }catch(Exception e){
	    System.err.println( e.getClass().getName() + ": " + e.getMessage() );
	  }
   }
}

Output :

F:\java-mongodb>javac mongodb_connection_drop_a_collection.java

F:\java-mongodb>java mongodb_connection_drop_a_collection
[system.indexes]

Drop a database

You can drop a collection by using the drop() method :

Code :

import com.mongodb.MongoClient;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBCursor;
import com.mongodb.ServerAddress;
import com.mongodb.WriteResult;
import java.util.Arrays;

public class mongodb_connection_drop_a_database{
   public static void main( String args[] ){
      try{   
  	     MongoClient mongoClient = new MongoClient();
         mongoClient.dropDatabase("testdb");
	    for (String s : mongoClient.getDatabaseNames()) {
        System.out.println(s);
        }	  
        }catch(Exception e){
	    System.err.println( e.getClass().getName() + ": " + e.getMessage() );
	  }
   }
}

Output :

F:\java-mongodb>javac mongodb_connection_drop_a_database.java

F:\java-mongodb>java mongodb_connection_drop_a_collection
[system.indexes]



Join our Question Answer community to learn and share your programming knowledge.

Help the community:

Python: Fizzbuzz

C++: Decimal to binary conversion

JavaScript: Need Help in JavaScript

Python: Help me with this program