January 18, 2017

How to update specific records of array field in collection using MongoDB

To update specific records of an array field in MongoDB, we can achieve that by using JavaScript with Mongo query. Below are the two ways to update the arrays. Lets see both ways to update the data.

Employee Collection:
 {  
           "_id" : 1,    
        "name" : {    
           "first" : "Abhi",    
           "last" : "Dev"    
        },    
        "profile":[ {"department" : "finance", "joineddate" : "2010-04-10"},  
                          {"department" : "marketing", "joineddate" : "2008-05-05"},  
                          {"department" : "hr", "joineddate" : "2006-08-05"}  
                          ]  
      },    
      {    
        "_id" : 2,    
        "name" : {    
           "first" : "Dhruv",    
           "last" : "Sharma"    
        },    
        "profile":[ {"department" : "retail", "joineddate" : "2013-07-10"},  
                          {"department" : "finance", "joineddate" : "2010-05-25"},  
                          {"department" : "hr", "joineddate" : "2007-08-05"}  
                          ]    
      }  

Objective is to update above array's joineddate field where department is finance.
Option 1: Updating the array using JavaScript:
 db.employee.find({}).  
      forEach(function(doc){  
           doc.profile.forEach(function(d){  
                if(d.department == "finance")  
                {       
                     d.joineddate = "2016-12-12"  
                }  
           });            
           db.employee.save(doc);  
      })   

Option 2: Updating array using Mongo Query operators update and set:
 var query = {  
   profile: {  
     $elemMatch: {  
       department: "finance",  
       joineddate: {$ne: "2016-12-12"}  
     }  
   }  
 };  
 while (db.employee.find(query).count() > 0) {  
   db.employee.update(  
     query,  
     { $set: { "profile.$.joineddate": "2016-12-12" } },  
     { multi: true }  
   );  
 }  

January 17, 2017

How to update field using data from same document's another field

We cannot directly use update method to update the field with same document's another field. We need to first iterate the data and then use save method to update the same.

For example:
Employee Collection

 {    
     "_id" : 1,               
     "name" : {   
          "full_name" : "AD",  
          "first" : "Abhi",    
           "last" : "Dev"    
      },    
      "department" : "finance",    
     "joineddate" : "2010-04-10"     
 }  
   

Lets say I have above collection document that I need to update. Full name of this document should be updated with First and Last field.
 db.employee.find().snapshot().forEach(  
  function (e) {  
   // update document, using its own properties  
   e.name.full_name = e.name.first + " " +e.name.last;  
   // save the updated document  
   db.employee.save(e);  
  }  
 )       

As you can see here, we are using snapshot query modifier. The $snapshot operator prevents the cursor from returning a document more than once because an intervening write operation results in a move of the document.

How to connect MongoDB with authentication in JAVA

To connect MongoDB through JAVA, we will use MongoClient and to fetch and iterate data we will use MongoCollection and FindIterable classes.

As of version 3.2, mongoclient.getDB method is deprecated. The deprecation of this method effectively deprecates the DB, DBCollection, and DBCursor classes, among others. That's the reason we will use the new methods and classes like MongoCollection, MongoDatabase and FindIterable correspondingly.

Full example of MongoDB connection in JAVA

Employee Collection
 {    
             "_id" : 1,    
             "name" : {    
                "first" : "Abhi",    
                "last" : "Dev"    
             },    
             "department" : "finance",    
             "joineddate" : "2010-04-10"     
            },    
            {    
             "_id" : 2,    
             "name" : {    
                "first" : "Alok",    
                "last" : "Agrawal"    
             },     
             "joineddate" : "2006-07-07"     
            },    
            {    
             "_id" : 3,    
             "name" : {    
                "first" : "Dhruv",    
                "last" : "Sharma"    
             },    
             "department" : "finance",    
             "joineddate" : "2010-09-07"     
            }  
           }   
JAVA code for Mongo Connection and fetching the data.

 
import org.bson.Document;

import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;

public class Test {

 public static void main(String[] args) {
String mongoClientURI = "mongodb://username:password@hostname:port/dbname";  
           MongoClient mongoClient = new MongoClient(new MongoClientURI(mongoClientURI));  
           MongoDatabase md = mongoClient.getDatabase("dbname");  
           MongoCollection<Document> mgColl = md.getCollection("employee");  
           Document assortCCObj = new Document("department", "finance");            
           assortCCObj.append("joineddate", new Document("$gt", "2010-01-01"));  
           FindIterable<Document> dt = mgColl.find(assortCCObj);  
           for (Document document : dt) {  
                System.out.println(document.toJson());  
           }  
    }
 }

The above code will connect to mongo and fetch data from employee collection as per the given criteria.