Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
205 views
in Technique[技术] by (71.8m points)

php - MongoDB updating fields in nested array

MongoDB updating fields in nested array

How can I set "play" to "play photo" in the photos array?

I only know its _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" 
}]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This issue has been resolved. Feature of updating fields inside 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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...