当我们在 mongodb 中删除某些内容或更新某些内容时,它会返回结果
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
我想知道如何访问 pymongo 中的这些字段来检查更新/删除是否成功或失败。
最佳答案
在 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
关于mongodb - pymongo 删除/更新命令返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32623665/