Array Modifiers Update MongoDB Java Example

This post is in continuation of our Update MongoDB Java Example series.

In the previous post we have Logical Querying MongoDB Java Exampleseen some of the Atomic update modifiers provided by MongoDB with the help of a Java example ,that can be used to
update and add new key to a
document. Now we will move one step ahead and will look into the Array modifiers available in MongoDB. Below are the following Array Modifiers that we are going to cover in this post.

  • $push
  • $each
  • $slice

Sample Document :

{
   "_id" : { "$oid" : "5356df76a2f83f17ecbea22d"} ,
  "firstName" : "rod" ,
  "lastName" : "johnson" ,
  "founder" : "Spring" ,
  "wiki" : "http://en.wikipedia.org/wiki/Rod_Johnson_%28programmer%29" ,
  "hits" : 45000
}

In this example we will add a new key “authorOf” that contains all the books written by Rod Johnson.

  1. $push :push array modifier always adds the element at the last of the array. If the key which you are adding doesn’t exist in the document it will create the key and associate a new array with it containing the value passed as an argument.
    DBObject modifiedObject =new BasicDBObject();
    modifiedObject.put("$push", new BasicDBObject().append("authorOf", "Introduction Of Spring Framework"));
    lotusCollection.update(searchObject, modifiedObject);

    Once the update method is executed it will create a new key authorOf and associate a new array with it containing our value. After update our document will look like this.

    { 
       "_id" : { "$oid" : "5357ffdba2f8ac4351986d63"} , 
       "firstName" : "rod" , 
       "lastName" : "johnson" , 
       "founder" : "Spring" , 
       "wiki" : "http://en.wikipedia.org/wiki/Rod_Johnson_%28programmer%29" ,
       "hits" : 45000 , 
       "authorOf" : [ "Introduction Of Spring Framework"]
    }

    Let’s execute the same code again with some different book name.

    modifiedObject.put("$push", new BasicDBObject().append("authorOf", "Expert One-on-One J2EE Development without EJB"));
    lotusCollection.update(searchObject, modifiedObject);

    Once the update method is executed it will add the new book at the end of our existing array referenced by key “authorOf” .Finally our document will have 2 books associated with it.

    { 
      "_id" : { "$oid" : "53580e8ea2f8ad723715a2b0"} , 
      "firstName" : "rod" ,
      "lastName" : "johnson" , 
      "founder" : "Spring" , 
      "wiki" : "http://en.wikipedia.org/wiki/Rod_Johnson_%28programmer%29" ,   
      "hits" : 45000 , 
      "authorOf" : [ "Introduction Of Spring Framework" , "Expert One-on-One  
                      J2EE Development without EJB"]
    }
  2. $each : each array modifier gives you the flexibility to add multiple values into the array in the same operation.
    DBObject eachObject =new BasicDBObject();
    eachObject.put("$each", new String[]{"Introduction Of Spring Framework","Expert One-on-One J2EE Development without EJB"});
    modifiedObject.put("$push", new BasicDBObject().append("authorOf", eachObject));
    lotusCollection.update(searchObject, modifiedObject);

    When the update method is executed it will add all the books to the array associated with “authorOf” key.Finally our document will look like this.

    { 
      "_id" : { "$oid" : "53580e8ea2f8ad723715a2b0"} , 
      "firstName" : "rod" ,
      "lastName" : "johnson" , 
      "founder" : "Spring" , 
      "wiki" : "http://en.wikipedia.org/wiki/Rod_Johnson_%28programmer%29" ,   
      "hits" : 45000 , 
      "authorOf" : [ "Introduction Of Spring Framework" , "Expert One-on-One  
                      J2EE Development without EJB"]
    }
  3. $slice : slice array modifier gives you the flexibility of restricting the size of the array. This way you can ensure that your array will always have the same number of elements that you specify with the slice.If we try to add the more element into array it will remove the older values from the array to make the place for the new ones.(First In First Out).Kindly note that $slice only takes negative value as its argument.
    DBObject modifiedObject =new BasicDBObject();
    DBObject eachObject =new BasicDBObject();
    eachObject.put("$each", new String[]{"Old Book 1","Old Book 2"});
    modifiedObject.put("$push", new BasicDBObject().append("authorOf", eachObject));
    lotusCollection.update(searchObject, modifiedObject);
    	    	    
    eachObject.put("$each", new String[]{"Introduction Of Spring Framework","Expert One-on-One J2EE Development without EJB"});
    eachObject.put("$slice", -3);	    
    modifiedObject.put("$push", new BasicDBObject().append("authorOf", eachObject));
    lotusCollection.update(searchObject, modifiedObject);

    In the above code first I have added “Old Book 1″ and “Old Book 2″ to the array and then i am trying to add 2 new books into the array , as in the slice i have mentioned my array size should not be more than 3 , so to meet this condition it will remove oldest book available book in the array i.e “Old Book 1″. Hence , you final document will look like this.

    { 
      "_id" : { "$oid" : "53580e8ea2f8ad723715a2b0"} , 
      "firstName" : "rod" ,
      "lastName" : "johnson" , 
      "founder" : "Spring" , 
      "wiki" : "http://en.wikipedia.org/wiki/Rod_Johnson_%28programmer%29" ,   
      "hits" : 45000 , 
      "authorOf" : [ "Old Book 2",
                     "Introduction Of Spring Framework" , 
                     "Expert One-on-One J2EE Development without EJB"]
    }

There is one more Array Modifier left out i.e $sort that we will cover in the upcoming post as we need to cover Java Pojos also before understanding that.

Complete Code :
ArrayModifiers.java

package com.lotusmedia.mongo;

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

public class ArrayModifiers {
	
	private static final String LOTUS_COLLECTION="lotusCollection";

	/**
	 *  Use of push array modifier
	 */
	private static void usingPushModifier(){
		DBCollection lotusCollection=MongoUtils.getCollection(LOTUS_COLLECTION);
		
		//search object
		DBObject searchObject =new BasicDBObject();
		searchObject.put("firstName", "rod");
		
		//Adding Books
		DBObject modifiedObject =new BasicDBObject();
		modifiedObject.put("$push", new BasicDBObject().append("authorOf", "Introduction Of Spring Framework"));
	    lotusCollection.update(searchObject, modifiedObject);
		
	    MongoUtils.printDocument("firstName", "rod");
	    
	    modifiedObject.put("$push", new BasicDBObject().append("authorOf", "Expert One-on-One J2EE Development without EJB"));
	    lotusCollection.update(searchObject, modifiedObject);
	    MongoUtils.printDocument("firstName", "rod");
		
	    //Recreating the collection and records
	    MongoUtils.dropAndRecreateCollection(LOTUS_COLLECTION);
	}
	
	/**
	 *  Use of each with push array modifier
	 */
	private static void usingEachWithPushModifier(){
		DBCollection lotusCollection=MongoUtils.getCollection(LOTUS_COLLECTION);
		
		//search object
		DBObject searchObject =new BasicDBObject();
		searchObject.put("firstName", "rod");
		
		//Adding Books
		DBObject modifiedObject =new BasicDBObject();
		DBObject eachObject =new BasicDBObject();
		eachObject.put("$each", new String[]{"Introduction Of Spring Framework","Expert One-on-One J2EE Development without EJB"});
		modifiedObject.put("$push", new BasicDBObject().append("authorOf", eachObject));
	    lotusCollection.update(searchObject, modifiedObject);
		
	    MongoUtils.printDocument("firstName", "rod");
	    
	  //Recreating the collection and records
	    MongoUtils.dropAndRecreateCollection(LOTUS_COLLECTION);
		
	}
	
	/**
	 *  Use of slice,each under push array modifier
	 */
	private static void usingSliceEachUnderPushModifier(){
		DBCollection lotusCollection=MongoUtils.getCollection(LOTUS_COLLECTION);
		
		//search object
		DBObject searchObject =new BasicDBObject();
		searchObject.put("firstName", "rod");
		
		//Adding Books
		DBObject modifiedObject =new BasicDBObject();
		DBObject eachObject =new BasicDBObject();
		eachObject.put("$each", new String[]{"Old Book 1","Old Book 2"});
		modifiedObject.put("$push", new BasicDBObject().append("authorOf", eachObject));
	    lotusCollection.update(searchObject, modifiedObject);
		
	    MongoUtils.printDocument("firstName", "rod");
	    
	    eachObject.put("$each", new String[]{"Introduction Of Spring Framework","Expert One-on-One J2EE Development without EJB"});
	    eachObject.put("$slice", -3);
	    
	    modifiedObject.put("$push", new BasicDBObject().append("authorOf", eachObject));
	    lotusCollection.update(searchObject, modifiedObject);		
	    MongoUtils.printDocument("firstName", "rod");
	    
	  //Recreating the collection and records
	    MongoUtils.dropAndRecreateCollection(LOTUS_COLLECTION);
		
	}	

	
	public static void main(String[] args) {
		ArrayModifiers.usingPushModifier();
		ArrayModifiers.usingEachWithPushModifier();
		ArrayModifiers.usingSliceEachUnderPushModifier();
	}

}

MongoUtils.java

package com.lotusmedia.mongo;

import java.net.UnknownHostException;

import com.mongodb.BasicDBObject;
import com.mongodb.BasicDBObjectBuilder;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;

public class MongoUtils {

	private static final String DATABASE_NAME="lotusDB";
	private static final String DEFAULT_COLLECTION_NAME="lotusCollection";
	private static MongoClient serverConnection = null;
	
	//TODO Thread Safety
	public static DBCollection getCollection(String collectionName) {
		if(serverConnection==null){
			try {
				serverConnection = new MongoClient("localhost",27017);
			} catch (UnknownHostException e) {
				e.printStackTrace();
				throw new RuntimeException("Not able to connect to localhost");
			}
		}		
		DB db = serverConnection.getDB(DATABASE_NAME);
		return db.getCollection(collectionName==null?DEFAULT_COLLECTION_NAME:collectionName);
	}
	
	
	public static void printDocument(String key,String value){
		System.out.println(getCollection("lotusCollection").findOne(new BasicDBObject().append(key, value)));
	}
	
	public static void dropAndRecreateCollection(String collectionName){
		DBCollection lotusCollection=MongoUtils.getCollection(collectionName);
		lotusCollection.drop();
		DBObject firstObject = BasicDBObjectBuilder.start().add("firstName", "rod").append("lastName", "johnson").
				append("founder", "Spring").append("wiki","http://en.wikipedia.org/wiki/Rod_Johnson_%28programmer%29").append("hits",45000).get();
		MongoUtils.getCollection("lotusCollection").insert(firstObject);
		firstObject = BasicDBObjectBuilder.start().add("firstName", "kevin").append("lastName", "ryan").
				append("founder", "mongo").append("wiki","http://en.wikipedia.org/wiki/Kevin_P._Ryan").append("hits",32000).get();
		MongoUtils.getCollection("lotusCollection").insert(firstObject);
		firstObject = BasicDBObjectBuilder.start().add("firstName", "james").
				append("lastName", "gosling").append("founder", "java").append("wiki","http://en.wikipedia.org/wiki/James_Gosling").append("hits",98000).get();
		MongoUtils.getCollection("lotusCollection").insert(firstObject);
		firstObject = BasicDBObjectBuilder.start().add("firstName", "doug").
				append("lastName", "cutting").append("founder", "Spring").append("wiki","http://en.wikipedia.org/wiki/Doug_Cutting").append("hits",28000).get();
		MongoUtils.getCollection("lotusCollection").insert(firstObject);
		firstObject = BasicDBObjectBuilder.start().add("firstName", "eliot").
				append("lastName", "Horowitz").append("founder", "mongo").append("wiki","http://en.wikipedia.org/wiki/Eliot_Horowitz").append("hits",38000).get();
		MongoUtils.getCollection("lotusCollection").insert(firstObject);
	}
}

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 “Array Modifiers 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>