PyMongo updates multiple records with multiple data

I am trying to store my dictionary data data in my database through PyMongo.

client = MongoClient('ip', port) db = client.test_database hdd = db.hdd products[{ 'Speed' : 'a', 'Capacity' : 'b', 'Format' : 'c' } { 'Speed' : 'd', 'Capacity' : 'e', 'Format': 'f'}] ... 

My database has an hdd table with 7 fields and 4 of them are already filled. The values ​​for Speed , capacity and format are "" and must be replaced with the data products . I want to fill in empty fields with dictionary data. Is there a way to update hdd like this, and if possible, how?

+5
source share
1 answer

I assume that you have some kind of "_id" value associated with each set of values, so you know which document in your collection is being updated? Let me call it "product_id". You can update individual documents, for example:

 for product, product_id in data: hdd.update({'_id': product_id}, {'$set': {'Speed': products['Speed'], 'capacity': products['capacity'], 'format': products['format']}}) 

The first argument to update is a query that indicates which document should match, the second is a set of update operations .

If you are using MongoDB 2.6 or later and the latest PyMongo, use the bulk update:

 bulk = hdd.initialize_ordered_bulk_op() for product, product_id in data: bulk.find({'_id': product_id}).update({'$set': {'Speed': products['Speed'], 'capacity': products['capacity'], 'format': products['format']}}) bulk.execute() 

Operations are buffered on the client, then all of them are sent to the server and executed simultaneously when you call "execute ()". Bulk update operations with PyMongo and MongoDB 2.6+ require fewer server visits than traditional updates.

+3
source

Source: https://habr.com/ru/post/1208586/


All Articles