举个例子,假设我们内存中有以下字典列表
dict_list = [
{
'id': 1,
'from_value_key': 'x'
},
{
'id': 2,
'from_value_key': 'y'
},
{
'id': 4,
'from_value_key': 'z'
}
]
db.collection
id: 1, other_key_and_values...
id: 2, other_key_and_values...
id: 3, other_key_and_values...
我想对上述数据库集合应用批量更新过程。
更新后的db集合内容如下
id: 1, other_key_and_values..., to_value_key: 'x'
id: 2, other_key_and_values..., to_value_key: 'y'
id: 3, other_key_and_values... #The id: 3 does not exist in the dictionary list side, so the setting of to_value_key does not occur.
#Ignore id: 4 because it exists only in the dictionary list.
我认为可以创建多个UpdateOne并使用bulk_write,但是是否可以在聚合管道中使用例如$lookup、$unwind、$merge等来批量执行更新过程?
假设
id
字段是唯一的,并且围绕它构建了唯一的索引,您可以将文档放入 $documents
阶段并将 $merge
放入集合中。
db.aggregate([
{
"$documents": [
// your python dict here
{
"id": 1,
"from_value_key": "x"
},
{
"id": 2,
"from_value_key": "y"
},
{
"id": 4,
"from_value_key": "z"
}
]
},
{
"$merge": {
"into": "collection",
"on": "id",
"whenMatched": "merge"
}
}
])
^ 这不起作用,因为游乐场尚未支持
$documents
。这只是为了演示语法。