Sunday 30 April 2017

Better way to update MongoDB subdocuments

I want to update particular subdocuments(multiple), For which I have two methods. I want to know which one is better to follow.

Sample Document

{ 
  _id: 1,
  doc: [{
       prop1: false,
       prop2: 1
  },{
       prop1: false,
       prop2: 1
  },{
       prop1: true,
       prop2: 2
  }]
}

Method1:

db.docs.findOne({}, function(err, result){
    if(err || !result) return next(err || []);
    result.doc.forEach(function(doc){
      if(doc.prop2 === 1){
        doc.prop1 = true;
      }
    });
    doc.save();
});

Method2:

db.docs.findOne({_id: 1}, function(err, result){
    if(err || !result) return next(err || []);
    var bulk = db.docs.initializeUnorderedBulkOp();
    result.doc.forEach(function(doc){
      if(doc.prop2 === 1){
         bulk.find({
            _id: 1,
            "doc.prop2": 1
            }).update({
                $set: {
                   "doc.$.prop1": true
                }
            });
      }
    });
    bulk.execute();
});

Please suggest. let me know if any query.



via Sachin

No comments:

Post a Comment