【问题标题】:Update multiple elements in an array in mongodb [duplicate]在mongodb中更新数组中的多个元素[重复]
【发布时间】:2018-12-14 20:28:17
【问题描述】:

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

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

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

【问题讨论】:

  • 如果每个数组中只有一个这样的子文档,则可以使用 mongodb 位置运算符 $。如果有多个,那么您很可能必须阅读该文档,在客户端更改其内容,然后保存回来(可能是一系列外科手术$set 命令,如$set: {'History.2.flag': 'true'}
  • Sergio Tulentsev,先生,您是在谈论历史阵列吗?不,该数组中有很多项目。我正在尝试使用 mongo shell 更改我的数据库,因此没有客户端。
  • Mongo shell 是客户端。
  • 不,先生,我正在使用 Nosqlbooster
  • @AnthonyWinzlet:哦,这是一个新的(对我来说)。谢谢,TIL。

标签: arrays mongodb mongodb-query


【解决方案1】:

您可以简单地使用“$”运算符来完成。比如:

 db.stocks.update( {"history.status" : { $not: "PROCESSED" } , 
                { $set: {"history.$.flag": true }} , 
                false , 
                true);

【讨论】:

  • 不适用于同一数组中的多个匹配项。
【解决方案2】:

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

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

【讨论】:

  • 先生,这是一个不错的参数,但我认为应该为“upsert”和“multi”添加两个额外的参数(基本上是 false 和 true,因为它们适合我)。我在这里写是因为“多”,所以它可以更改多个文档。
  • 您可以对多个文档使用multitrue,但不知道为什么upserthere?
  • Sir 使用 'upser' 为 false 可以确保即使没有任何文档满足条件,也不会创建新文档
  • 宾果游戏!这是更新数组中每个元素的完美答案。
  • 简单的 P E R F E C T
【解决方案3】:

你可以使用脚本来实现它。

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

【讨论】:

  • 我发现这是最好的。最适合我的问题
【解决方案4】:

我的回答与@Anthony 非常相似,但是 添加了两个额外的参数(upsertmulti)。供参考您可以查看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.
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-19
    • 1970-01-01
    • 2016-01-16
    • 2016-11-18
    • 1970-01-01
    • 1970-01-01
    • 2020-04-18
    • 1970-01-01
    相关资源
    最近更新 更多