2 回答

TA貢獻1875條經驗 獲得超5個贊
我們可以使用$[identifier]運算符來更新數組中的特定對象
所以你的更新查詢應該看起來像
db.collection.updateOne(
{ _id: <OBJECT_ID> }, // filter part, add the real objectId here
{ $set: { 'orders.$[order].handleName': 'Donald Stark' } }, // update part
{ arrayFilters: [{ 'order.userId': 1, 'order.handleName': 'John Doe' }]
})
$[order] 僅更新與數組過濾器中的條件匹配的對象
更新
如果你有一個內部數組,并且你需要對該內部數組中的元素做同樣的事情,我們可以使用類似的東西
db.collection.updateOne(
{ _id: <OBJECT_ID> }, // filter part, add the real objectId here
{ $set: {
'orders.$[order].handleName': 'Donald Stark', // to set the handleName in the elements of the outer array
'orders.$[].others.$[other].handleName': 'Donald Stark' // to set the handleName in the elements of the inner array
} },
{ arrayFilters: [{ 'order.userId': 1, 'order.handleName': 'John Doe' }, { 'other.userId': 1, 'other.handleName': 'John Doe' }] }
)
我們曾經$[]循環遍歷訂單數組中的所有元素,然后$[other]根據數組過濾器中的新條件更新內部數組中的特定元素
希望能幫助到你

TA貢獻2003條經驗 獲得超2個贊
這樣的事情能解決你的問題嗎?
d = {
"_id": <OBJECT_ID>,
"orders": [
{
"userId": 1,
"handleName": "John Doe",
"orderAmount": 3
},
{
"userId": 2,
"handleName": "Maria Gigante",
"orderAmount": 2
},
{
"userId": 1,
"handleName": "John Doe",
"orderAmount": 4
},
{
"userId": 3,
"handleName": "John Doe",
"orderAmount": 4
}
]
}
def change_name(usr_id, old_name, new_name):
for usr in d['orders']:
if usr['userId'] == usr_id and usr['handleName'] == old_name:
usr['handleName'] = new_name
change_name(1, 'John Doe', 'Donald Stark')
添加回答
舉報