4

Suppose I have the following document

{
   _id: ObjectId("5234cc89687ea597eabee675"),
   code: "xyz",
   tags: [ "school", "book", "bag", "headphone", "appliance" ],
   qty: [
          { size: "S", num: 10, color: "blue" },
          { size: "M", num: 45, color: "blue" },
          { size: "L", num: 100, color: "green" }
        ]
}

{
   _id: ObjectId("5234cc8a687ea597eabee676"),
   code: "abc",
   tags: [ "appliance", "school", "book" ],
   qty: [
          { size: "6", num: 100, color: "green" },
          { size: "6", num: 50, color: "blue" },
          { size: "8", num: 100, color: "brown" }
        ]
}

{
   _id: ObjectId("5234ccb7687ea597eabee677"),
   code: "efg",
   tags: [ "school", "book" ],
   qty: [
          { size: "S", num: 10, color: "blue" },
          { size: "M", num: 100, color: "blue" },
          { size: "L", num: 100, color: "green" }
        ]
}

I want to change the num of all the elements in the document having the code "efg" to 0. How do I do that ? Should I use a loop with the positional operator ?

styvane
  • 59,869
  • 19
  • 150
  • 156
Sanjit Roy
  • 177
  • 1
  • 2
  • 11

1 Answers1

5

The best way to do this is match the array element and update individually with the positional $ operator using the Bulk() API . You really shouldn't blow your qty array.

var bulk = db.mycollection.initializeOrderedBulkOp(),   
    count = 0;

db.mycollection.find({ "code" : "efg" }).forEach(function(doc){ 
    var qty = doc["qty"]; 
    for (var idx = 0; idx < qty.length; idx++){ 
        bulk.find({ 
            "_id": doc._id, 
            "qty": { "$elemMatch": { "num": qty[idx]["num"]}}
        }).update({ "$set": { "qty.$.num": 0 }})
    }     
    count++;  
    if (count % 200 == 0) { 
        // Execute per 200 operations and re-init.
        bulk.execute(); 
        bulk = db.mycollection.initializeOrderedBulkOp(); 
    } 
})

// Clean up queues
if (count % 200 != 0)
    bulk.execute(); 
styvane
  • 59,869
  • 19
  • 150
  • 156