在mongodb中更新数组中的多个元素 [英] Update multiple elements in an array in mongodb

查看:43
本文介绍了在mongodb中更新数组中的多个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 mongodb 的股票集合中有一个类似以下的文档.

I have a document like following in my stocks collection in mongodb.

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

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

I want to iterate through all document in stocks collection and add a field flag: true if status is not 'PROCESSED'.

推荐答案

您可以使用脚本来实现.

You can achieve it using script.

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

这篇关于在mongodb中更新数组中的多个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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