如何通过列表键值更新嵌套数组?
{
"_id": "mainId",
"events": [{
"id": 1,
"profile": 10,
} {
"id": 2,
"profile": 10,
} {
"id": 3,
"profile": 20,
}
]
}我有一个列表需要更新:
var list = {id: 2, newval: 222}, {id: 3, newval: 333}如何在一个查询中执行更新?或者在MongoDB中,它会像一个循环?
for({id, val} in list){
update({_id: "mainId", events.$.id: id}, {setField: {events.$.profile: val}})
}发布于 2020-07-07 21:34:50
如果您有events数组的副本,则可以在代码中进行必要的更新,然后在单个查询中将更新后的数组发送到MongoDB。像这样的东西
db.Test.updateOne({_id: "mainId"}, {$set: { "events": [{id: 1, profile: 222}, {id: 2, profile: 10}, {id: 3, profile: 333}] } } )如果您没有事件数组的副本,则可以执行批量操作。就像这样
db.Test.bulkWrite(
[
{ updateOne : {
"filter": {_id: "mainId", "events.id": 1},
"update": { $set: { "events.$.profile": 222 } }
}
},
{ updateOne : {
"filter": {_id: "mainId", "events.id": 3},
"update": { $set: { "events.$.profile": 333 }}
}
}
]
)有关bulkWrite的更多信息,请参阅MongoDB文档:https://docs.mongodb.com/manual/core/bulk-write-operations/#bulkwrite-methods
https://stackoverflow.com/questions/62775562
复制相似问题