python - 如何使用 PyMongo 迭代和更新文档?

标签 python mongodb pymongo

我有一个用于 MongoDB 和 PyMongo 2.6.3 的简单单客户端设置。目标是迭代集合 collection 中的每个文档并更新(保存)过程中的每个文档。我使用的方法大致如下:

cursor = collection.find({})
index = 0
count = cursor.count()
while index != count:
    doc = cursor[index]
    print 'updating doc ' + doc['name']
    # modify doc ..
    collection.save(doc)
    index += 1
cursor.close()

问题是 save 显然是在修改光标中文档的顺序。 例如,如果我的集合由 3 个文档组成 (id 为清楚起见省略了):

{
    "name": "one"
}
{
    "name": "two"
}
{
    "name": "three"
}

以上程序输出:

> updating doc one
> updating doc two
> updating doc two

但是,如果删除 collection.save(doc) 行,输出将变为:

> updating doc one
> updating doc two
> updating doc three

为什么会这样?安全迭代更新集合中文档的正确方法是什么?

最佳答案

在 MongoDB 中找到了答案 documentation :

Because the cursor is not isolated during its lifetime, intervening write operations on a document may result in a cursor that returns a document more than once if that document has changed. To handle this situation, see the information on snapshot mode.

在光标上启用了快照模式,并做出了很好的保证:

snapshot() traverses the index on the _id field and guarantees that the query will return each document (with respect to the value of the _id field) no more than once.

使用 PyMongo 启用快照模式:

cursor = collection.find(spec={},snapshot=True)

根据 PyMongo find() documentation .确认这解决了我的问题。

关于python - 如何使用 PyMongo 迭代和更新文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20592404/

相关文章:

python - `assert_frame_equal` 和 `equals` 有什么区别

c# - Mongo DB 文档反序列化为 C# 对象的一个​​属性失败

MongoDB - 仅检索匹配的子文档和根文档

json - 在python中将pymongo查询集序列化为json

python - Groupby 包含两个特定值 - pandas

python - 为什么 GAE 没有检测到我的表单页面?

javascript - Next js - 如何在 url 中为 api 传递多个参数?

python - pymongo 的安装有效但在 python3 中导入时失败

mongodb - 自动重新连接 : No replica set members available for query with ReadPreference PRIMARY_PREFERRED

javascript - 访问django for循环中的元素