user3138937
user3138937

Reputation: 21

pymongo remove/update command returns

When we delete something or update something in mongodb.It returns the as result

WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

I want to know how to access those fields in pymongo to check weather the update/delete was sccess or failure.

Upvotes: 2

Views: 392

Answers (1)

Sede
Sede

Reputation: 61225

Prior pymongo 3.0 you need to access the number of modified document with the nModified key.

In [19]: import pymongo

In [20]: pymongo.version
Out[20]: '2.8'

In [21]: client = pymongo.MongoClient()

In [22]: db = client.test

In [23]: col = db.bar

In [24]: col.insert({'a': 4})
Out[24]: ObjectId('55fa5f890acf45105e95eab5')

In [25]: n = col.update({}, {'$set': {'a': 3}})

In [26]: n['nModified']
Out[26]: 1

From pymongo 3.0 you need to use the modified_count attribute

In [27]: n = col.update_one({}, {'$set': {'a': 8}})

In [28]: n.modified_count
Out[28]: 1

Upvotes: 3

Related Questions