简体   繁体   English

Mongo使用$运算符针对多个条件更新数组子元素

[英]Mongo update array subelement using $ operator for multiple conditions

I have following data in my mongo collection: 我的mongo集合中有以下数据:

{
    "services" : [ 
        {
            "service" : "service1",
            "instanceId" : 0,
            "attributes" : {
                "attr" : {
                    "value" : "val1"
                }
            }
        }, 
        {
            "service" : "service1",
            "instanceId" : 1,
            "attributes" : {
                "attr" : {
                    "value" : "val2"
                }
            }
        }, 

    ]
}

and I am trying to run following query to update data of instanceid 1, using $ operator: 我正在尝试运行以下查询以使用$运算符更新instanceid 1的数据:

db.device.update({"services.service":"service1", "services.instanceId":1},{"$set":{"services.$.attributes.attr.value":"val3"}},{})

But this query always updates instance id 0 of array. 但是此查询始终更新数组的实例ID 0。 I am not able to find any other way to update this. 我找不到其他任何方式来更新此内容。

Use $elemMatch to target the array element matching on multiple conditions. 使用$elemMatch可以在多个条件下定位匹配的数组元素。

Something like 就像是

db.device.update(
  {"services":{"$elemMatch":{"service":"service1", "instanceId":1}}},
  {"$set":{"services.$.attributes.attr.value":"val3"}}
)

Update : 更新

Try this: 尝试这个:

db.runCommand({
   update:"sample", //provide collection name here
   updates:[{q:{}, u:{$set:
    {"services.$[element].attributes.attr.value":"val3"}}, arrayFilters: [ { 
     "element.instanceId": 1, "element.service": "service1" } ], multi:true}]  
 })

or this: 或这个:

db.sample.update(
 {},
 {$set:{"services.$[element].attributes.attr.value":"val3"}},
 {arrayFilters: [ { "element.instanceId": 1, "element.service": "service1" } 
 ], multi:true}

)

在此处输入图片说明 在此处输入图片说明

Thanks to @mickl for the comments and info. 感谢@mickl的评论和信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM