简体   繁体   English

如何在Mongodb中更新多个大子元素

[英]How to update multiple grand child elements in Mongodb

I'm trying to update MongoDB grandchildren documents to update grand element values.我正在尝试更新 MongoDB 孙文档以更新大元素值。 For example, I need to update all the "ware" values to "LUX" where "ware" is "LAX".例如,我需要将所有“ware”值更新为“LUX”,其中“ware”为“LAX”。

In other words I need to change "ware": "LAX", ---> "ware": "LUX", However "ware": "NYC", should not change换句话说,我需要更改 "ware": "LAX", ---> "ware": "LUX",但是 "ware": "NYC",不应更改

here is the example data.这是示例数据。

[
{
"_id": ObjectId("5db72c636309f84479ec0c7b"),
"productCode": "aaaa",
"brand": "Nike",
"image": "some.jpg",
"sizes": [
    {
    "_id": ObjectId("5db72c636309f84479ec0c7e"),
    "size": "41",
    "wares": [
        {
        "_id": ObjectId("5db72c636309f84479ec0c80"),
        "ware": "LAX",
        "amount": 100
        },
        {
        "_id": ObjectId("5db72c636309f84479ec0c7f"),
        "ware": "NYC",
        "amount": 7
        }
    ]
    },
    {
    "_id": ObjectId("5db72c636309f84479ec0c7c"),
    "size": "42",
    "wares": [
        {
        "_id": ObjectId("5db72c636309f84479ec0c7d"),
        "ware": "LAX",
        "amount": 16
        }
    ]
    }
]
},
{
"_id": ObjectId("5db72c636309f84479ec0c7X"),
"productCode": "aaaa",
"brand": "Nike",
"image": "some.jpg",
"sizes": [
    {
    "_id": ObjectId("5db72c636309f84479ec0c7D"),
    "size": "41",
    "wares": [
        {
        "_id": ObjectId("5db72c636309f84479ec0c8G"),
        "ware": "LAX",
        "amount": 100
        },
        {
        "_id": ObjectId("5db72c636309f84479ec0c7R"),
        "ware": "NYC",
        "amount": 7
        }
      ]
    },
    {
    "_id": ObjectId("5db72c636309f84479ec0c7q"),
    "size": "42",
    "wares": [
        {
        "_id": ObjectId("5db72c636309f84479ec0c7n"),
        "ware": "LAX",
        "amount": 16
        }
      ]
    }
  ]
}
]

I've tried this我试过这个

db.getCollection('products').findAndModify({
query: { sizes: { $elemMatch: { wares:  {$elemMatch: { ware: "LAX" }}}}},
update: { $set: { "sizes.wares.$.ware": 'LUX' } }
})

Try this one:试试这个:

db.getCollection('products').updateMany(
   {},
   { $set: { "sizes.$[].wares.$[item].ware": 'LUX' } },
   { arrayFilters: [{ "item.ware": "LAX" }] }
)

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

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