【发布时间】: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