Search code examples
pythonmongodbpymongo

How to access WriteResult in PyMongo?


I have the following in my python file:

result = db.clients.update_one({'id':client['client']['id']},{'$set':{
    "name" : client['client']['name'],
}},True)

I want to retrieve how many records were inserted and how many were updated. I know I have to use WriteResults, but I can't seem to figure out how.

*this is one a loop *The update/insert works. I just don't know how to get the status of inserts vs updates

I am new to python and new to pymongo :)


Solution

  • You should be able to access the values you want by

    result.modified_count
    

    and

    result.upserted_id   #Will be None if no upsert took place
    

    And don't forget that the built in dir method is a great tool to use when you want to see all the methods and properties available to you on a Python object. Try this:

    print dir(result)
    

    EDIT
    See documentation here: https://pymongo.readthedocs.io/en/stable/api/pymongo/results.html?highlight=pymongo.results#pymongo.results.BulkWriteResult