0

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?

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.