MongoDB
 sql >> Teknologi Basis Data >  >> NoSQL >> MongoDB

Gabungkan koleksi Mongodb dan Python Dict

Anda dapat mencoba kode di bawah ini :

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 : operasi penulisan massal



  1. Redis
  2.   
  3. MongoDB
  4.   
  5. Memcached
  6.   
  7. HBase
  8.   
  9. CouchDB
  1. Memesan hasil yang ditetapkan secara acak di mongo

  2. Mengonversi DBObject ke Java Object sambil mengambil nilai dari MongoDB

  3. MongoDB $round vs $trunc:Apa Bedanya?

  4. Kueri dalam Fungsi Pengurangan Peta MongoDB

  5. Mongodb $lookup dengan dokumen bersarang