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

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

问题描述

我有一个带有嵌套聚合的文档,我想将所有属性全部设置为true.我已经尝试过使用$ set的几种方法,但是我无法对其进行更新. 如何实现?

I have a document with nested aggregations and I would like to set the all the attributes full to true. I have tried several methods using $set, but I am not able to update it. How can this be achieved?

{
"_id" : ObjectId("5b4347734e69052e544da67e"),
"providerId" : ObjectId("5b4242b9d8ff1b0020daab34"),
"aggregations" : [ 
    {
        "startTime" : "2012-01-01T00:00:00Z",
        "endTime" : "2012-03-01T00:00:00Z",
        "quantity" : 0,
        "full" : false
    }, 
    {
        "startTime" : "2012-01-01T00:00:00Z",
        "endTime" : "2012-03-01T00:00:00Z",
        "quantity" : 0,
        "full" : false
    }
],
"__v" : 0

}

推荐答案

您可以尝试使用 $[] The all positional 运算符,用于更新数组中的多个文档

You can try using $[] The all positional operator which updates multiple documents inside the array

db.collection.update(
  { },
  { "$set": { "aggregations.$[].full": true }}
)

,如果您想增加

db.collection.update(
  { "aggregations.full": false },
  { "$inc": { "aggregations.$.quantity": 2 }}
)

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

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