2

当我们在 mongodb 中删除某些内容或更新某些内容时,它会返回结果

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

我想知道如何访问 pymongo 中的这些字段以检查更新/删除是否成功或失败的天气。

4

1 回答 1

3

在 pymongo 3.0 之前,您需要使用nModified密钥访问修改文档的数量。

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

从 pymongo 3.0 开始,您需要使用该 modified_count属性

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

In [28]: n.modified_count
Out[28]: 1
于 2015-09-17T06:41:54.473 回答