如何将 mongodb 文档中的所有数组元素更改为某个值? [英] How to change all the array elements in a mongodb document to a certain value?

查看:60
本文介绍了如何将 mongodb 文档中的所有数组元素更改为某个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下文件

{
   _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"的所有元素的数量更改为 0.我该怎么做?我应该使用带有位置运算符的循环吗?

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 ?

推荐答案

最好的方法是匹配数组元素并单独更新位置 $ 操作符使用 Bulk() API .你真的不应该破坏你的 qty 数组.

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

这篇关于如何将 mongodb 文档中的所有数组元素更改为某个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆