I would like to update multiple documents in a mongoDB database using pymongo. I have this data:
data_to_be_updated = [
{"sourceID" : 6, "source" : "test", "name" : "simon"},
{"sourceID" : 8, "source" : "test", "name" : "greg"},
{"sourceID" : 9, "source" : "test", "name" : "julie"},
{"sourceID" : 10, "source" : "test", "name" : "john"}
]
sourceIDs = [6, 8, 9, 10]
I would like to update each of the elements in data_to_be_inserted
, filtering them by their sourceID
. I have tried using the update_many
function, but it updates all documents matching a single filter. I could of course use a for loop like this:
for item in data_to_be_updated:
collection.update_one({"sourceID": item["sourceID"]}, item})
The above method uses to many calls. How do i achieve the same in a single call to the database?
Use bulk_write. Something like this, depending on exactly what fields need to be updated:
from pymongo.operations import UpdateOne
data_to_be_updated = [
{"sourceID": 6, "source": "test", "name": "simon"},
{"sourceID": 8, "source": "test", "name": "greg"},
{"sourceID": 9, "source": "test", "name": "julie"},
{"sourceID": 10, "source": "test", "name": "john"}
]
result = collection.bulk_write([
UpdateOne(filter={'sourceID': d['sourceID']},
update={'$set': {'name': d['name'],
'source': d['source']}})
for d in data_to_be_updated])
print(result.bulk_api_result)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments