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.

No comments:

Post a Comment