I have a simple, single-client setup for MongoDB and PyMongo 2.6.3. The goal is to iterate over each document in the collection and update ( save ) each document in the process. The approach I'm using looks something like this:
cursor = collection.find({}) index = 0 count = cursor.count() while index != count: doc = cursor[index] print 'updating doc ' + doc['name']
The problem is that save seems to reorder the documents in the cursor. For example, if my collection consists of 3 documents ( id omitted for clarity):
{ "name": "one" } { "name": "two" } { "name": "three" }
above program outputs:
> updating doc one > updating doc two > updating doc two
If, however, the collection.save(doc) is deleted, the output becomes:
> updating doc one > updating doc two > updating doc three
Why is this happening? What is the right way to safely iterate and update documents in a collection?
python mongodb pymongo
paislee
source share