I'm trying to update MongoDB grandchildren documents to update grand element values. For example, I need to update all the "ware" values to "LUX" where "ware" is "LAX".
In other words I need to change "ware": "LAX", ---> "ware": "LUX", However "ware": "NYC", should not change
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" }] }
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.