Java MongoDB : Insert Document(s) in Collection Examples

In MongoDB learning series, we have already covered the MongoDB basics, MongoDB installation in windows, and how to query/select documents from a collection. In this tutorial, I am listing 4 ways you can utilize to insert or add document(s) into a collection in MongoDB.

List of examples in this tutorial

1) Insert BasicDBObject in collection
2) Use DBObjectBuilder to insert document in collection
3) Use java.util.HashMap to build BasicDBObject and insert into collection
4) Parse JSON to build DBObject and insert into collection

Sample document which we will insert into collection

{
    "name":"lokesh",
    "website":"howtodoinjava.com",
    "address":{
        "addressLine1":"Some address",
        "addressLine2":"Karol Bagh",
        "addressLine3":"New Delhi, India"
    }
}

1) Insert BasicDBObject in collection

This one is simplest. Create an instance of BasicDBObject, populate data and call collection.insert() method.

BasicDBObject document = new BasicDBObject();
document.put("name", "lokesh");
document.put("website", "howtodoinjava.com");

BasicDBObject documentDetail = new BasicDBObject();
documentDetail.put("addressLine1", "Sweet Home");
documentDetail.put("addressLine2", "Karol Bagh");
documentDetail.put("addressLine3", "New Delhi, India");

document.put("address", documentDetail);

collection.insert(document);

Output:

{ "_id" : { "$oid" : "538d56a3364192189d4f98fe"} , "name" : "lokesh" , "website" : "howtodoinjava.com" , 
"address" : { "addressLine1" : "Sweet Home" , "addressLine2" : "Karol Bagh" , "addressLine3" : "New Delhi, India"}}

2) Use DBObjectBuilder to insert document in collection

Very similar to above example, only uses DBObjectBuilder to build DBObject.

BasicDBObjectBuilder documentBuilder = BasicDBObjectBuilder.start()
		.add("name", "lokesh")
		.add("website", "howtodoinjava.com");
 
BasicDBObjectBuilder documentBuilderDetail = BasicDBObjectBuilder.start()
.add("addressLine1", "Some address")
.add("addressLine2", "Karol Bagh")
.add("addressLine3", "New Delhi, India");

documentBuilder.add("address", documentBuilderDetail.get());

collection.insert(documentBuilder.get());

Output:

{ "_id" : { "$oid" : "538d56a3364192189d4f98ff"} , "name" : "lokesh" , "website" : "howtodoinjava.com" , 
"address" : { "addressLine1" : "Sweet Home" , "addressLine2" : "Karol Bagh" , "addressLine3" : "New Delhi, India"}}

3) Use java.util.HashMap to build BasicDBObject and insert into collection

Here, you fist put the data in hashmap and then use this hashmap to build BasicDBObject.

Map<String, Object> documentMap = new HashMap<String, Object>();
documentMap.put("name", "lokesh");
documentMap.put("website", "howtodoinjava.com");

Map<String, Object> documentMapDetail = new HashMap<String, Object>();
documentMapDetail.put("addressLine1", "Some address");
documentMapDetail.put("addressLine2", "Karol Bagh");
documentMapDetail.put("addressLine3", "New Delhi, India");

documentMap.put("address", documentMapDetail);

collection.insert(new BasicDBObject(documentMap));

Output:

{ "_id" : { "$oid" : "538d56a3364192189d4f98fg"} , "name" : "lokesh" , "website" : "howtodoinjava.com" , 
"address" : { "addressLine1" : "Sweet Home" , "addressLine2" : "Karol Bagh" , "addressLine3" : "New Delhi, India"}}

4) Parse JSON to build DBObject and insert into collection

String json = "{ 'name' : 'lokesh' , " +
				"'website' : 'howtodoinjava.com' , " +
				"'address' : { 'addressLine1' : 'Some address' , " +
							  "'addressLine2' : 'Karol Bagh' , " +
							  "'addressLine3' : 'New Delhi, India'}" +
							"}";
	 
DBObject dbObject = (DBObject)JSON.parse(json);

collection.insert(dbObject);

Output:

{ "_id" : { "$oid" : "538d56a3364192189d4f98fg"} , "name" : "lokesh" , "website" : "howtodoinjava.com" , 
"address" : { "addressLine1" : "Sweet Home" , "addressLine2" : "Karol Bagh" , "addressLine3" : "New Delhi, India"}}

Complete Example and Sourcecode

The complete working code for all above examples is as below:

package examples.mongodb.crud;

import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;

import com.mongodb.BasicDBObject;
import com.mongodb.BasicDBObjectBuilder;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.WriteResult;
import com.mongodb.util.JSON;

public class MongoDBInsertDataExample 
{
	public static void main(String[] args) throws UnknownHostException 
	{
		MongoClient mongo = new MongoClient("localhost", 27017);
		DB db = mongo.getDB("howtodoinjava");
		DBCollection collection = db.getCollection("users");
		
		///Delete All documents before running example again
		WriteResult result = collection.remove(new BasicDBObject());
		System.out.println(result.toString());
		
		basicDBObject_Example(collection);
		
		basicDBObjectBuilder_Example(collection);
		
		hashMap_Example(collection);
		
		parseJSON_Example(collection);
		
		DBCursor cursor = collection.find();
		while(cursor.hasNext()) {
		    System.out.println(cursor.next());
		}
	}
	
	private static void basicDBObject_Example(DBCollection collection){
		BasicDBObject document = new BasicDBObject();
		document.put("name", "lokesh");
		document.put("website", "howtodoinjava.com");
	 
		BasicDBObject documentDetail = new BasicDBObject();
		documentDetail.put("addressLine1", "Sweet Home");
		documentDetail.put("addressLine2", "Karol Bagh");
		documentDetail.put("addressLine3", "New Delhi, India");
	 
		document.put("address", documentDetail);
	 
		collection.insert(document);
	} 
	
	private static void basicDBObjectBuilder_Example(DBCollection collection){
		BasicDBObjectBuilder documentBuilder = BasicDBObjectBuilder.start()
				.add("name", "lokesh")
				.add("website", "howtodoinjava.com");
		 
		BasicDBObjectBuilder documentBuilderDetail = BasicDBObjectBuilder.start()
		.add("addressLine1", "Some address")
		.add("addressLine2", "Karol Bagh")
		.add("addressLine3", "New Delhi, India");
	 
		documentBuilder.add("address", documentBuilderDetail.get());
	 
		collection.insert(documentBuilder.get());
	}
	
	private static void hashMap_Example(DBCollection collection){
		Map<String, Object> documentMap = new HashMap<String, Object>();
		documentMap.put("name", "lokesh");
		documentMap.put("website", "howtodoinjava.com");
	 
		Map<String, Object> documentMapDetail = new HashMap<String, Object>();
		documentMapDetail.put("addressLine1", "Some address");
		documentMapDetail.put("addressLine2", "Karol Bagh");
		documentMapDetail.put("addressLine3", "New Delhi, India");
	 
		documentMap.put("address", documentMapDetail);
	 
		collection.insert(new BasicDBObject(documentMap));
	}
	
	private static void parseJSON_Example(DBCollection collection){
		String json = "{ 'name' : 'lokesh' , " +
						"'website' : 'howtodoinjava.com' , " +
						"'address' : { 'addressLine1' : 'Some address' , " +
									  "'addressLine2' : 'Karol Bagh' , " +
									  "'addressLine3' : 'New Delhi, India'}" +
									"}";
			 
		DBObject dbObject = (DBObject)JSON.parse(json);
	 
		collection.insert(dbObject);
	}
	
}

Output:

{ "serverUsed" : "localhost/127.0.0.1:27017" , "connectionId" : 3 , "n" : 4 , "syncMillis" : 0 , "writtenTo" :  null  , "err" :  null  , "ok" : 1.0}
{ "_id" : { "$oid" : "538d5b3936417871aa391d20"} , "name" : "lokesh" , "website" : "howtodoinjava.com" , "address" : { "addressLine1" : "Sweet Home" , "addressLine2" : "Karol Bagh" , "addressLine3" : "New Delhi, India"}}
{ "_id" : { "$oid" : "538d5b3936417871aa391d21"} , "name" : "lokesh" , "website" : "howtodoinjava.com" , "address" : { "addressLine1" : "Some address" , "addressLine2" : "Karol Bagh" , "addressLine3" : "New Delhi, India"}}
{ "_id" : { "$oid" : "538d5b3936417871aa391d22"} , "address" : { "addressLine3" : "New Delhi, India" , "addressLine2" : "Karol Bagh" , "addressLine1" : "Some address"} , "website" : "howtodoinjava.com" , "name" : "lokesh"}
{ "_id" : { "$oid" : "538d5b3936417871aa391d23"} , "name" : "lokesh" , "website" : "howtodoinjava.com" , "address" : { "addressLine1" : "Some address" , "addressLine2" : "Karol Bagh" , "addressLine3" : "New Delhi, India"}}

Happy Learning !!

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

9 thoughts on “Java MongoDB : Insert Document(s) in Collection Examples”

  1. good examples .. i am trying to use the 2nd concept (Use DBObjectBuilder to insert document in collection ) to build and test sample applications. Able to insert the records during the first trigger call from java but if changing the record data and try to insert the MongoDB documents are not getting inserted again with the changed data.

    Please suggest.

    Reply
  2. hey i want to write a program in java to insert data from csv file, xml file, excel file into mongodb. Plz help me how would….

    Reply
  3. how to get id object of a particular collection by mapping first name. I have user collection and user attendance collections. I already created all users and their details as user collection, now i need to create another collection in the same db but now i want to put same _id object to the new collection according to same name its mean same person which i have inserted to the user collection.
    i thought you can help me..
    best regards
    one of your student (through your posts)

    Reply
  4. Thanks for providing such a nice example. I wonder it should be done using Spring “org.springframework.data.mongodb.core”. Could you please post example on this too?

    Reply
  5. Thanks for the above tutorial.

    How ever, i am trying to insert into an embedded document in a loop. When I use collection.update(), the previously inserted embedded document gets overwritten by the new document. My document structure is

    Key_1: Value_1
    Key_2: {
    A1:B1
    A2:B2
    A3:B3
    }

    Keys A1, A2 and A3 gets inserted in a loop along with their values. The issue I am facing is, everytime A1:B1 gets overwritten by A2:B2 and then end of update, database only has A3:B3. What is the way to insert all three in a loop so that it does not override the previous one? Can you please show how to do it in Java?

    Reply

Leave a Comment

HowToDoInJava

A blog about Java and related technologies, the best practices, algorithms, and interview questions.