【问题标题】:Mongodb: Update Many documents with each element in given listMongodb:使用给定列表中的每个元素更新许多文档
【发布时间】:2021-05-16 06:27:48
【问题描述】:

我有这个 DEVICE 收藏

[
{
  "_id": ObjectId("60265a12f9bf1e3974dabe56"),
  "Name": "Device",
  "Configuration_ids": [
      ObjectId("60265a11f9bf1e3974dabe54"),
      ObjectId("60265a11f9bf1e3974dabe55")
  ]
},
{
  "_id": ObjectId("60265a92f9bf1e3974dabe64"),
  "Name": "Device2",
  "Configuration_ids": [
      ObjectId("60265a92f9bf1e3974dabe5a"),
      ObjectId("60265a92f9bf1e3974dabe5b")
  ]
},
{
  "_id": ObjectId("60265a92f9bf1e3974dabe65"),
  "Name": "Device3",
  "Configuration_ids": [
      ObjectId("60265a92f9bf1e3974dabe5e"),
      ObjectId"60265a92f9bf1e3974dabe5f")
  ]
}
]

我需要更新与设备 ID 列表匹配的所有文档。并将每个元素推送到每个匹配设备中的 configuration_ids 给定列表中。这两个列表的长度相同。

我的解决方案写在下面,但我可以在一个查询中完成吗?

device_ids=[
        ObjectId("60265a12f9bf1e3974dabe56"),
        ObjectId("60265a92f9bf1e3974dabe64"),
        ObjectId("60265a92f9bf1e3974dabe65")
    ]

configuration_ids = [
        ObjectId("60267d14bc2f40d0dec1de3b"),
        ObjectId("60267d14bc2f40d0dec1de3c"),
        ObjectId("60267d14bc2f40d0dec1de3d")
   ]
for i in range(0, len(device_ids)):
   update_devices = device_collection.update_one(
       {'_id': ObjectId(device_ids[i])},
       {'$push': {'Configuration_ids': configuration_ids[i]}}
    )

结果:

[
{
  "_id": ObjectId("60265a12f9bf1e3974dabe56"),
  "Name": "Device",
  "Configuration_ids": [
      ObjectId("60265a11f9bf1e3974dabe54"),
      ObjectId("60265a11f9bf1e3974dabe55"),
      ObjectId("60267d14bc2f40d0dec1de3b")
  ]
},
{
  "_id": ObjectId("60265a92f9bf1e3974dabe64"),
  "Name": "Device2",
  "Configuration_ids": [
      ObjectId("60265a92f9bf1e3974dabe5a"),
      ObjectId("60265a92f9bf1e3974dabe5b"),
      ObjectId("60267d14bc2f40d0dec1de3c")
  ]
},
{
  "_id": ObjectId("60265a92f9bf1e3974dabe65"),
  "Name": "Device3",
  "Configuration_ids": [
      ObjectId("60265a92f9bf1e3974dabe5e"),
      ObjectId"60265a92f9bf1e3974dabe5f"),
      ObjectId("60267d14bc2f40d0dec1de3d")
  ]
}
]

【问题讨论】:

    标签: python arrays mongodb pymongo


    【解决方案1】:

    如果您希望使用update_many 在一次更新中实现此目的,那么简短的回答是您不能。 update_many 采用单个过滤器来确定要更新哪些文档;在您的示例中,每次更新都是不同的文档 ID。

    如果您有大量此类更新,并且存在性能问题,请考虑使用bulk write operators

    【讨论】:

      猜你喜欢
      • 2020-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-22
      • 2016-08-29
      • 2019-02-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多