首页 > 解决方案 > 更新mongodb数组中的多个元素

问题描述

我在 mongodb 的股票集合中有如下文件。

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

如果状态不是,我想遍历stocks集合中的所有文档并添加一个字段。flag: true'PROCESSED'

标签: arraysmongodbmongodb-query

解决方案


您需要使用 all $[] 位置运算符来更新数组中的每个元素

db.collection.update(
   { "History": { "$elemMatch": { "status": { "$ne": "PROCESSED" } } } }, 
   { "$set": { "History.$[].flag": false } },
   { "multi": true }
)

推荐阅读