MongoDB
 sql >> Database >  >> NoSQL >> MongoDB

Unisci la raccolta Mongodb e un Python Dict

Puoi provare sotto il codice:

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

Rif: operazioni di scrittura in blocco