【发布时间】:2013-12-15 07:52:53
【问题描述】:
我有一个简单的 MongoDB 和 PyMongo 2.6.3 单客户端设置。目标是遍历集合collection 中的每个文档并更新(save)过程中的每个文档。我使用的方法大致如下:
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 个文档组成(为清楚起见,省略了 ids):
{
"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
为什么会这样?安全地迭代和更新集合中的文档的正确方法是什么?
【问题讨论】:
-
这不是答案。但是试试
1 + 999 is 1000和``1 + 999 == 1000`。 -
@falsetru thx 只是为了简单而重新创建,仍在学习 python :)。现在好吗?
-
你是如何修改文档的?
doc['name'] = 'newValue'够了吗?