【问题标题】:Which is the efficient way of updating an element in MongoDB?在 MongoDB 中更新元素的有效方法是什么?
【发布时间】:2022-01-07 10:10:22
【问题描述】:

我有一个像下面这样的集合

{
    "doc_id": "1234",
    "items": [
        {
            "item_no": 1,
            "item": "car",
        },
        {
            "item_no": 2,
            "item": "bus",
        },
        {
            "item_no": 3,
            "item": "truck",
        }
    ]
},

我需要根据搜索条件更新项目列表中的元素。我的搜索条件是,如果“item_no”为 3,则“item”应更新为“aeroplane”。 我在 Python 中编写了以下两种方法来解决这个问题。

方法一:

cursor = list(collection.find({"doc_id": 1234}))
for doc in cursor:
    if "items" in doc:
        temp = deepcopy(doc["items"])
        for element in doc["items"]:
            if ("item_no" and "item") in element:
                if element["item_no"] == 3:
                    temp[temp.index(element)]["item"] = "aeroplane"
                    collection.update_one({"doc_id": 1234},
                                          {"$set": {"items": temp}})

方法二:

cursor = list(collection.find({"doc_id": 1234}))
for doc in cursor:
    if "items" in doc:
       collection.find_one_and_update({"doc_id": 1234}, {'$set': {'items.$[elem]': {"item_no": 3, "item": "aeroplane"}}}, array_filters=[{'elem.item_no': {"$eq": 3}}])

以上两种方式,哪一种在时间复杂度上更好?

【问题讨论】:

    标签: arrays python-3.x mongodb pymongo


    【解决方案1】:

    仅使用查询并避免循环:

    db.collection.update({
      "doc_id": "1234",
      "items.item_no": 3
    },
    {
      "$set": {
        "items.$.item": "aeroplane"
      }
    })
    

    例如here

    注意如何在查找阶段使用"items.item_no": 3,您可以在更新阶段使用$ 将对象引用到数组中。

    所以,做

    {
      "doc_id": "1234",
      "items.item_no": 3
    }
    

    当您使用$ 时,您是在告诉 mongo:“好的,在条件匹配的对象中执行您的操作”(即,集合中的对象与 doc_id: "1234" 和数组与 items.item_no: 3

    此外,如果您想更新多个文档,您可以使用multi:true,例如this example

    编辑:您似乎正在使用pymongo,因此您可以使用multi=Truemulti: true)或更简洁的方式,使用update_many

    collection.update_many( /* your query here */ )
    

    【讨论】:

      猜你喜欢
      • 2010-10-05
      • 1970-01-01
      • 2015-10-14
      • 2019-06-30
      • 1970-01-01
      • 1970-01-01
      • 2016-11-03
      • 2012-11-19
      • 1970-01-01
      相关资源
      最近更新 更多