MongoDB update array if condition matches

var candidate = 2;

rc=db.foo.update({}, // add matching criteria here; for now, match ALL                                
         [ 
         [
             // We cannot say "if condition then set fld = X else do nothing".    
             // We must say "set fld to something based on condition."            
             // The common pattern becomes:                                       
             //   "Set fld to (if condition then X else fld)"                     
             // in other words, set the fld to *itself* 
             //
             // Note the use of the dot operator on the $locations field.
             // Also, not sure about what sort of new timestamp is desired so let's
             // just throw in an ISODate() for now.                          
             {$set: {'locations': {$cond: [
                 {$ne:[candidate, {$last:'$locations.controllerID'}]}, // IF not same as candidate...                                                                             
                 {$concatArrays: ['$locations',
// $concatArrays wants arrays, not objects, so we must wrap our new
// object with [] to make an array of 1:
                                  [ {controllerId:candidate,timestamp:new ISODate() } ]
                                 ]}, // THEN concat a new entry to end of existing locations                                                                       
                 '$locations' // ELSE just set back to existing locations         
                 ]}
             }}
         ],
         {multi:true}
);
Topics: MongoDB

Related Code Examples