我似乎无法弄清楚如何更新子阵列中的单个元素。我想将images > 59db1c3654819952005897 > sort
更新为5
"_id" : 34,
"images": [
{
"59db1c3654819952005897": {
"name": "1024x1024.png",
"size": "19421",
"sort": 2
}
},
{
"59db1c3652cda581935479": {
"name": "200x200.png",
"size": "52100",
"sort": 3
}
}
]
这是我尝试但未奏效的事情:
updateOne(['_id' => 34], ['$set' => ["images.59db1c3654819952005897.sort" => 5]])
updateOne(['_id' => 34], ['$set' => ["images.$.59db1c3654819952005897.sort" => 5]])
答案 0 :(得分:1)
使用positional $
operator和dot notation更新嵌入文档字段时,您需要在查询中包含该数组,否则它将无效。在上述情况下,修订后的更新操作将是
db.collection.updateOne(
{
"_id": 34,
"images.59db1c3654819952005897": { "$exists": true } // <-- include array in query
},
{
"$set": {
"images.$.59db1c3654819952005897.sort": 5
}
}
)