代码之家  ›  专栏  ›  技术社区  ›  Mritunjay Upadhyay

在MongoDB中更新数组中的多个元素[重复]

  •  2
  • Mritunjay Upadhyay  · 技术社区  · 6 年前

    这个问题已经有了答案:

    我在mongodb的stocks集合中有一个类似如下的文档。

    { _id: 'xRMuRBhqRLgASyQyW',
      History: 
         [ { orderId: '12032017001877',
             status: 'COMPLETED',
            },
           { orderId: '22122017002450', 
            status: 'PROCESSED',
            },
            { orderId: '22122018002450', 
            status: 'DEPOSIT',
            }  
         ] 
     }
    

    我想遍历 stocks 收集并添加字段 flag: true 如果状态不是 'PROCESSED' 是的。

    4 回复  |  直到 6 年前
        1
  •  1
  •   Vikas    6 年前

    你可以用脚本来实现它。

    db.stocks.find().forEach(function(e){var modified=false;e.History.forEach(function(o){if(o.status!="PROCESSED"){o.flag=true;modified=true}});if(modified){db.stocks.save(e)}});
    
        2
  •  8
  •   Ashh    6 年前

    你需要用所有的 $[] positional 运算符更新数组中的每个元素

    db.collection.update(
       { "History": { "$elemMatch": { "status": { "$ne": "PROCESSED" } } } }, 
       { "$set": { "History.$[].flag": false } },
       { "multi": true }
    )
    
        3
  •  1
  •   Pouya Jabbarisani    6 年前

    您只需使用“$”运算符即可完成此操作。类似:

     db.stocks.update( {"history.status" : { $not: "PROCESSED" } , 
                    { $set: {"history.$.flag": true }} , 
                    false , 
                    true);
    
        4
  •  0
  •   Mritunjay Upadhyay    6 年前

    我的回答和安东尼很相似,但是 额外的两个参数 upsert multi )添加了。作为参考,你可以检查 official document 是的。

    db.stocks.update(
        { "History": { "$elemMatch": { "status": { "$ne": "PROCESSED" } } } }, 
        { "$set": { "History.$[].flag": false }},
         false,              // show that if there is not any document with specified criteria , it will not create a new document.
         ture              // according to document of mongodb if multi is true then more than one document will be updated, other wise only one document will be updated.
    )