合并 Mongodb 集合和 Python 字典 [英] Merge Mongodb collection and a Python Dict
问题描述
我有一个看起来像这样的集合:
I have a collection that look something like that :
{
{"name": "aaa", "value": 100},
{"name": "bbb", "value": 50},
{"name": "ccc", "value": 200},
}
想象一下我有一个这样的字典:
and imagine I have a dict like this one :
{
{"name": "aaa", "value": 40},
{"name": "ccc", "value": -100},
{"name": "ddd", "value": 200},
}
我想以某种方式将字典合并到集合中,它添加名称未出现在集合中的文档,并合并名称相等的文档之间的 2 值.集合应该像这样结束:
I would like to merge the dict into the collections in a way it add the documents in which the name does not appear in the collection, and merge the 2 value between documents that had a name equal. The collection should end up like this :
{
{"name": "aaa", "value": 140},
{"name": "bbb", "value": 50},
{"name": "ccc", "value": 100},
{"name": "ddd", "value": 200},
}
我已经检查了 replace_many、insert_many 和 update_many,但看起来不可能让它们表现得像我想做的那样.
I've checked the replace_many, insert_many and the update_many but it looks like it's not possible to make them behave like what I want to do.
目前,我正在对所有不存在的文档进行基本的 insert_many 操作,并对存在的每个文档进行 replace_one 操作,但我想做一些更优化的操作.
For the moment I'm doing a basic insert_many of all the document that are not present and a replace_one for each document that is present but I would like to do something more optimized.
先谢谢你
推荐答案
你可以试试下面的代码:
You can try below code :
import pymongo
from pymongo import UpdateOne
import json
import sys
inputArray = [
{"name": "aaa", "value": 40},
{"name": "ccc", "value": -100},
{"name": "ddd", "value": 200},
]
bulkArr = []
# Iterate over all dicts in a list & form the query,
# Here `upsert=True` helps to insert a new doc into collection if there is no match on `{"name": x['name']}`,
# If there is a match doc will be updated, You can use `$set` or any-other operator depends on your use case.
for x in inputArray:
bulkArr.append(
UpdateOne({"name": x['name']}, {'$inc': {'value': x['value']}}, upsert=True))
# print('[%s]' % ', '.join(map(str, bulkArr)))
try:
result = db.collection.bulk_write(bulkArr) # Ensure db connection is established by this point
# Opt for below - if you want to proceed on all dictionaries to be updated, even though an error occured in between for one dict
# result = db.collection.bulk_write(bulkArr, ordered=False)
print(result.bulk_api_result)
except:
e = sys.exc_info()[0]
print("An exception occurred ::", e) ## Get the ids failed if any & do re-try
参考: 批量写入操作
这篇关于合并 Mongodb 集合和 Python 字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!