sql >> Database >  >> NoSQL >> MongoDB

Mongodb-verzameling en een Python-dictaat samenvoegen

Je kunt onderstaande code proberen:

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

Ref: bulk-write-operations



  1. Leg uit alsof ik vijf ben:formulier met tekst- en afbeeldingsveld> Routes> Controller> Schrijf naar MongoDB-document - waar gaat GridFS naartoe?

  2. Sorteren op Meerdere velden mongo DB

  3. Datumbereikquery mislukt voor MongoDB-database met tweets

  4. Lopende meteoor in een cluster en realtime veranderingen