【问题标题】:Updating array of sub sub document with matching element使用匹配元素更新子子文档的数组
【发布时间】:2019-06-21 18:01:02
【问题描述】:

以下是我的架构:

{  
   "_id":ObjectId("5c49c783de72ec2ec47b95d1"),
   "placement":[  
      {  
         "offer":[  
            {  
               "sent_by":"John",
               "comment":""
            },
            {  
               "sent_by":"Mary",
               "comment":""
            }
         ]
      }
   ]
}

我想更新placement.offer.comment,其中placement.offer.sent_byMary,但它总是更新第一条记录。我不想提供像placement.0.offer.1.sent_by 这样的硬编码数字。

这应该是生成的文档:

{  
   "_id":ObjectId("5c49c783de72ec2ec47b95d1"),
   "placement":[  
      {  
         "offer":[  
            {  
               "sent_by":"John",
               "comment":""
            },
            {  
               "sent_by":"Mary",
               "comment":"Some comment updated"
            }
         ]
      }
   ]
}

【问题讨论】:

标签: mongodb mongoose-schema


【解决方案1】:

您需要使用array filters 来实现:

db.collection.update(
    { /* add additional query filters here */ },
    { $set: { "placement.$[].offer.$[o].comment": "Some updated comment" } },
    { arrayFilters: [ { "o.sent_by": "Mary" } ] }
)

【讨论】:

  • @Sid: 你用的是什么客户端?哪个 MongoDB 版本?
  • 感谢您对此进行调查,MongoDB 版本是 3.4.15
  • @Sid:数组过滤器是在 MongoDB v3.6 中引入的——你能更新吗?
猜你喜欢
  • 2019-02-16
  • 2015-12-22
  • 1970-01-01
  • 2020-12-05
  • 2016-07-13
  • 2017-04-23
  • 2021-02-25
  • 2018-05-27
  • 1970-01-01
相关资源
最近更新 更多