在 MongoDB 中更新元素的有效方法是啥?

Posted

技术标签:

【中文标题】在 MongoDB 中更新元素的有效方法是啥?【英文标题】: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])

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

【问题讨论】:

【参考方案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 */ )

【讨论】:

以上是关于在 MongoDB 中更新元素的有效方法是啥?的主要内容,如果未能解决你的问题,请参考以下文章

在 OpenGL 中绘制 3d 图形的最有效方法是啥?

将数据从 MongoDB 发送到 Hadoop 的有效方法是啥?

MongoDB - 更新集合中所有记录的最快方法是啥?

在实时 mongodb 机器上更新(或替换)整个数据库集合的最佳方法是啥?

在Javascript中更新对象数组中的键的最有效方法是啥? [复制]

在 Go 中访问二维数组中的相邻元素的最有效方法是啥?