向上插入文档数组

2024-04-19 12:48:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用Python构建MongoDB支持的API。我收到了一系列的文件和其他几个ID。结构如下:

{
    a_id: ObjectId("..."),
    b_id: ObjectId("..."),
    all_items: [
        {item_id: ObjectId("..."), other_val: "I am other value"},
        {item_id: ObjectId("..."), other_val: "I am another value"},
        ...
    ]
}

我只想做的是:根据a_id, b_id & item_id值在集合中增加插入。因此,数据将按照以下方式在集合中进行结构化:

{
    a_id: ObjectId("..."),
    b_id: ObjectId("..."),
    item_id: ObjectId("..."),
    other_val: "..."
}

因此,如果存在与a_id, b_id & item_id匹配的文档,则将更新,否则将插入。你知道吗

我需要为每个upsert遍历整个all_items数组吗?请告知。你知道吗


Tags: 文件apiidvaluemongodbanotheritemsval
1条回答
网友
1楼 · 发布于 2024-04-19 12:48:05

您不必在数组中循环;您可以将filter()lambda expression结合使用,然后将其与其他条件结合使用:

编辑:代码示例已更新

import pymongo
from bson import ObjectId

db = pymongo.MongoClient()['mydatabase']

# Data setup
my_dict = {
    'a_id': ObjectId("111111111111111111111111"),
    'b_id': ObjectId("222222222222222222222222"),
    'all_items': [
        {'item_id': ObjectId("333333333333333333333333"), 'other_val': "I am other value"},
        {'item_id': ObjectId("444444444444444444444444"), 'other_val': "I am another value"}
    ]
}

# Filter criteria setup
a_filter = ObjectId("111111111111111111111111")
b_filter = ObjectId("222222222222222222222222")
item_filter = ObjectId("444444444444444444444444")

db.mycollection.delete_many({})

for z in filter(lambda x: x.get('item_id') == item_filter, my_dict['all_items']):
    db.mycollection.replace_one({'a_id': a_filter, 'b_id': b_filter, 'item_id': item_filter},
                                {'a_id': a_filter, 'b_id': b_filter, 'item_id': item_filter,
                                 'other_val': z.get('other_val')},
                                upsert=True)

    break  # Remove this line if you want all matching items not just the first one found

提供:

> db.mycollection.findOne({}, {'_id': 0})
{
        "a_id" : ObjectId("111111111111111111111111"),
        "b_id" : ObjectId("222222222222222222222222"),
        "item_id" : ObjectId("444444444444444444444444"),
        "other_val" : "I am another value"
}

相关问题 更多 >