我有一个用于 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/