如何将mongodb文档中的所有数组元素更改为某个值?

时间:2015-09-16 13:55:47

标签: javascript node.js mongodb mongodb-query

假设我有以下文件

{
   _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" }
        ]
}

我想将代码为“efg”的文档中所有元素的num更改为0.我该怎么办?我应该使用位置运算符的循环吗?

1 个答案:

答案 0 :(得分:5)

执行此操作的最佳方法是匹配数组元素,并使用$ API单独更新位置Bulk()运算符。你真的不应该吹你的qty数组。

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();