使用pymongo批量更新,合并python字典和DB集合

问题描述 投票:0回答:1

举个例子,假设我们内存中有以下字典列表

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等来批量执行更新过程?

mongodb pymongo
1个回答
0
投票

假设

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
。这只是为了演示语法。

© www.soinside.com 2019 - 2024. All rights reserved.