首页 > 解决方案 > 使用匹配元素更新子子文档的数组

问题描述

以下是我的架构:

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

我想更新placement.offer.commentwhere placement.offer.sent_byisMary但它总是更新第一条记录。我不想提供像placement.0.offer.1.sent_by.

这应该是生成的文档:

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

标签: mongodbmongoose-schema

解决方案


您需要使用数组过滤器来实现:

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

推荐阅读