Python 向上插入文档数组
我正在用Python构建MongoDB支持的API。我收到了一系列的文档和一些其他ID。结构如下:Python 向上插入文档数组,python,mongodb,pymongo,Python,Mongodb,Pymongo,我正在用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
{
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\u id、b\u id和item\u id
值在集合中升级。因此,数据将按照以下方式在集合内部结构化:
{
a_id: ObjectId("..."),
b_id: ObjectId("..."),
item_id: ObjectId("..."),
other_val: "..."
}
因此,如果存在与a\u id、b\u id和item\u id
匹配的文档,则该文档将被更新,否则将被插入
我是否需要为每个upsert循环整个
所有\u项
数组?请告知 不必在数组中循环;可以将a与a一起使用,然后将其与其他条件结合使用:
编辑:代码示例已更新
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"
}
因此,如果这三者都匹配,则会为特定的
项目id
更新other\u val
,或者插入带有{a\u id:ObjectId(“…”),b\u id:ObjectId(“…”),item\u id:ObjectId(“…”),other\u val:“…”
的新文档?@srinivasy yes,正确。问题解决了吗?或者您还需要任何帮助吗?我关心的不是塑造数据,而是在MongoDB中升级数据。我已经更新了exampel代码以包含升级。