Upsert MongoDB Java Example

This post will talk about upsert mongodb java example.
Consider a scenario where we have to MongoDB Official Logo
write the logic such that – we will
search for a record in the database
and if it is available in database we
will update it else we will insert a
new record with same information.
Conventional solution for this type of problem is first you will try to find the record in MongoDB either using findOne() or find() , and on the basis of this find() result you will execute an update or an insert statement.
Problem with the above solution is that you are making 2 round trips to the database ,1st for searching the record and 2nd for executing update or insert.

Upsert :
MongoDB provides an alternative way of doing the same through upsert statements. Basically upserts are special types of update operations where it tries to first update a document if matching document is found otherwise it inserts a new record into database. This way you can use the same code for both inserting and updating the documents.

Here, also we will use the same collection that we have used in our previous examples.You can refer this collection here.

In my collection I want to add one more record ,but I am not sure whether it this record already exists or not in my collection. So, here I will use upsert so that if the record exists it will increment the numberOfHits of their Wikipedia page else it will insert a new record into it.

DBCollection lotusCollection=MongoUtils.getCollection("yoMongo");
BasicDBObject searchObject = new BasicDBObject();
searchObject.put("title", "Sir");
searchObject.put("firstName", "Dennis");
searchObject.put("lastName", "Ritchie");
searchObject.put("founder", "C");
searchObject.put("wiki", "http://en.wikipedia.org/wiki/Dennis_Ritchie");
		
DBObject modifiedObject =new BasicDBObject();
modifiedObject.put("$inc", new BasicDBObject().append("hits", 1));
		
lotusCollection.update(searchObject, modifiedObject,true,false);
MongoUtils.printDocument("firstName", "Dennis");

When I execute the above mentioned method , it will insert a new record for “Sir Dennis Ritchie” in my collection as it doesn’t exist already and increment the “hits” counter by 1. Below is the output that we will get when the function is executed.

{ 
   "_id" : { "$oid" : "535fb7b105146c5b8e43b8d1"} , 
   "firstName" : "Dennis" , 
   "founder" : "C" , 
   "lastName" : "Ritchie" , 
   "title" : "Sir" , 
   "wiki" : "http://en.wikipedia.org/wiki/Dennis_Ritchie" , 
   "hits" : 1
}

When I execute the above method again this time it won’t insert any record as for the provided information it will find a record and just increment the “hits” counter by 1. Here is the output.

{ 
   "_id" : { "$oid" : "535fb7b105146c5b8e43b8d1"} , 
   "firstName" : "Dennis" , 
   "founder" : "C" , 
   "lastName" : "Ritchie" , 
   "title" : "Sir" , 
   "wiki" : "http://en.wikipedia.org/wiki/Dennis_Ritchie" , 
   "hits" : 2
}

To enable the upsert , we have to use the overloaded version of update() method . Here is the Java specification for update method. Kindly notice in our example we have passed 3rd argument as true , that ensures that we want to enable upsert and if you pass it as a false then it will work as a normal update operation.upsert mongodb java example

Complete Code :

/**
 * 
 */
package com.lotusmedia.mongo;

import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;

/**
 * @author yoMongo
 *
 */
public class UpsertExample {

	public static void updateOrInsert(){
		DBCollection lotusCollection=MongoUtils.getCollection("yoMongo");
		BasicDBObject searchObject = new BasicDBObject();
		searchObject.put("title", "Sir");
		searchObject.put("firstName", "Dennis");
		searchObject.put("lastName", "Ritchie");
		searchObject.put("founder", "C");
		searchObject.put("wiki", "http://en.wikipedia.org/wiki/Dennis_Ritchie");
		
		DBObject modifiedObject =new BasicDBObject();
		modifiedObject.put("$inc", new BasicDBObject().append("hits", 1));
		
		lotusCollection.update(searchObject, modifiedObject,true,false);
		MongoUtils.printDocument("firstName", "Dennis");
		
	}
	
	
	public static void main(String[] args) {
		UpsertExample.updateOrInsert();
	}

}

For MongoUtils.java you can refer here.

Let'sConnect

Saurabh Jain

A Developer working on Enterprise applications ,Distributed Systems, Hadoop and BigData.This blog is about my experience working mostly on Java technologies ,NoSQL ,git , maven and Hadoop ecosystem.
Let'sConnect

Share and Enjoy

  • Facebook
  • Twitter
  • Delicious
  • LinkedIn
  • StumbleUpon
  • Add to favorites
  • Email
  • RSS

One thought on “Upsert MongoDB Java Example

Add Comment Register



Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>