gpt4 book ai didi

php - MongoDB 更新嵌套数组中的字段

转载 作者:可可西里 更新时间:2023-11-01 09:07:39 25 4
gpt4 key购买 nike

MongoDB 更新嵌套数组中的字段

如何在 photos 数组中将“play”设置为“play photo”?

我只知道它的_id

"_id": ObjectId("4f41a5c7c32810e404000000"),
"albums": [
{
"_id": ObjectId("4f545d1bc328103812000000"),
"name": "album1" ,
"photos":[{
"_id": ObjectId("4f545d1bc328103812d00000"),
"name":"travel photo"
},{
"_id": ObjectId("4f545d1bc328103812c00000"),
"name":"play"
}]
},
{
"_id": ObjectId("4f545f56c328103c12000000"),
"name": "album2"
},
{
"_id": ObjectId("4f545f68c328103012000000"),
"name": "album3"
},
{
"_id": ObjectId("4f546642c328103c12000001"),
"name": "album4"
}]

最佳答案

This issue has been resolved. Feature of updating fieldsinside nested array of objects, is available in MongoDB 3.6+ versions.Look positional operators(all and with identifier) here.

//Update all docs in collection matching photo name "play" to "play photo"
db.collectioname.update(
{},
{ $set: { "albums.$[].photos.$[photo_field].name": "play photo" } },
{ arrayFilters: [ {"photo_field.name": "play"} ], multi: true}
);

//Update this specific doc given in question matching photo name "play" to "play photo"
db.collectioname.update(
{"_id" : ObjectId("4f41a5c7c32810e404000000")},
{ $set: { "albums.$[].photos.$[photo_field].name": "play photo" } },
{ arrayFilters: [ {"photo_field.name": "play"} ]}
);

This is for the help of people coming here after MongoDB 3.6

关于php - MongoDB 更新嵌套数组中的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9611833/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com