Atomic Update MongoDB Java Example

In the previous post i.e Document Logical Querying MongoDB Java Example
Replacement in MongoDB
we have
seen how we were updating the
document – first by getting the
document using findOne() , then
updating its values and finally
putting it back in the collection.
We can also achieve the same task
in a single step i.e skipping findOne() invocation and by using atomic update modifiers provided by mongodb. This post will focus on update mongodb java example.
Here we will look at some of the atomic update modifiers that are available in MongoDB with the help of a Java example.

  • $set
  • $unset
  • $inc

We will continue with the same example that we have used in other posts also.
Sample Document :

{ 
  "_id" : { "$oid" : "5356df76a2f83f17ecbea22d"} , 
  "firstName" : "rod" , 
  "lastName" : "johnson" , 
  "founder" : "Spring" , 
  "wiki" : "http://en.wikipedia.org/wiki/Rod_Johnson_%28programmer%29" , 
  "hits" : 45000
}
  1. $set : set operator plays dual role. If the field that you wish to update exists in your document then it will update it with the new value else it will create a new field with the same name and value in your document.
    In our example , I am interested in adding one more key “authorOf” to my existing documents.One way we can do this by using the same approach that we had taken in the previous post , but here we will try to do this with the help of set atomic update modifier. Below is the Java code for same.

    DBObject modifiedObject =new BasicDBObject();
    modifiedObject.put("$set", new BasicDBObject().append("authorOf", "Introduction Of Springg Framework"));
    lotusCollection.update(searchObject, modifiedObject);
    

    Above mentioned code will create the new key in all the documents matched by our search criteria.For the first time as this key doesn’t exist , so it will create this new key in the document.
    If you have noticed I misspelled the book name it should be Spring (Springg –> Spring) , so to correct it I will execute the update statement again.

    modifiedObject.put("$set", new BasicDBObject().append("authorOf", "Introduction Of Spring Framework"));

    This time it won’t create a new key as this key already exists in our document and only updates the value for this key.
    With $set atomic update modifier, we can add any type of a value to a key. In the above example we can also add an array of books, as all we know Rod Johnson is also an author of one of the bestselling book on J2EE i.e “Expert One-on-One J2EE Development without EJB”.

    modifiedObject.put("$set", new BasicDBObject().append("authorOf", new String[]{"Introduction Of Spring Framework","Expert One-on-One J2EE Development without EJB"}));

    , so we will add this book also.

  2. $unset : unset atomic update modifier removes a particular key from the document which is passed as an argument. Let’s remove the authorOf key that we have just added from the document.
    modifiedObject.put("$unset", new BasicDBObject().append("authorOf", 1));
    lotusCollection.update(searchObject, modifiedObject);
    

    Above mentioned code will remove the authorOf key in the document.

  3. $inc: inc atomic update modifier works only on the numeric values. With this operator you can increase or decrease the value of a key by a certain number. It will also create a new key if the requested key is not available in the document.
    In our example we have hits as one of the key in all the documents , now we want to increment this counter as soon somebody visits the Wikipedia page of Rod Johnson.

    DBObject modifiedObject =new BasicDBObject();
    modifiedObject.put("$inc", new BasicDBObject().append("hits", 1));
    lotusCollection.update(searchObject, modifiedObject);
    

    Above mentioned code will increment the value of hits by 1, you can pass any other number also instead of 1. For decrement you have to pass the negative number.

Complete Code :

package com.lotusmedia.mongo;

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

public class UpdateModifiers {
	
	/**
	 * Sets the authorOf key with the document associated with Rod Johnson.
	 */
	private static void updateUsingSetModifier(){
		DBCollection lotusCollection=MongoUtils.getCollection("lotusCollection");
		//search object
		DBObject searchObject =new BasicDBObject();
		searchObject.put("firstName", "rod");		
		
		DBObject modifiedObject =new BasicDBObject();
		modifiedObject.put("$set", new BasicDBObject().append("authorOf", new String[]{"Introduction Of Spring Framework","Expert One-on-One J2EE Development without EJB"}));
	    lotusCollection.update(searchObject, modifiedObject);
	    printDocument();
	}

	/**
	 * Unsets the authorOf key with the document associated with Rod Johnson.
	 */
	private static void updateUsingUnsetModifier(){
		DBCollection lotusCollection=MongoUtils.getCollection("lotusCollection");
		//search object
		DBObject searchObject =new BasicDBObject();
		searchObject.put("firstName", "rod");
		
		DBObject modifiedObject =new BasicDBObject();		
		modifiedObject.put("$unset", new BasicDBObject().append("authorOf", 1));
		lotusCollection.update(searchObject, modifiedObject);
		printDocument();
	}
	
	/**
	 * Increments the hits key of the document by 1.
	 */
	private static void updateUsingIncModifier(){
		DBCollection lotusCollection=MongoUtils.getCollection("lotusCollection");
		//search object
		DBObject searchObject =new BasicDBObject();
		searchObject.put("firstName", "rod");		
		
		DBObject modifiedObject =new BasicDBObject();
		modifiedObject.put("$inc", new BasicDBObject().append("hits", 1));
	    lotusCollection.update(searchObject, modifiedObject);
	    printDocument();
	}
	
	private static void printDocument(){
		System.out.println(MongoUtils.getCollection("lotusCollection").findOne(new BasicDBObject().append("firstName", "rod")));
	}
	
	public static void main(String[] args) {
		UpdateModifiers.updateUsingSetModifier();
		UpdateModifiers.updateUsingUnsetModifier();
		UpdateModifiers.updateUsingIncModifier();
	}

}

Image Source : http://mongodb.org


 

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

One thought on “Atomic Update 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>