I am trying to store data the data of my dictionary in my database via 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 a table hdd
with 7 fields and 4 of them are already filled. The values of Speed
, capacity
and format
are ""
and need to be replaced with the data of products
. I want to fill the empty fields with the data of the dictionary. Is there a way to update hdd
like that, and if it's possible, how?
I assume you have some sort of "_id" value associated with each set of values, so you know which document in your collection to update? Let's call that "product_id". You can update individual documents like:
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 specifies which document to match, the second is a set of update operations .
If you're on MongoDB 2.6 or later and the latest PyMongo, use a 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()
The operations are buffered on the client, then they're all sent to the server and executed at once when you call "execute()". Bulk update operations with PyMongo and MongoDB 2.6+ require fewer round trips to the server than traditional updates.
initialize_ordered_bulk_op
shows as deprecated in my PyCharm (I have pymongo 3.9). Bulk updates can be done as follows:
replacements = [{ ObjectId("5fa994e96bfcb746d4935778"): "new_value"}]
bulk_ops = []
for _id, new_value in replacements.items():
bulk_ops.append(
UpdateOne(
{"_id": _id},
{"$set": {"old_key": new_value, "other_key": other_value}},
)
)
result = db.coll.bulk_write(bulk_ops)
pprint(result.bulk_api_result)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.