title: How to iterate and update documents with PyMongo?
body: <p>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 <code>collection</code> and update (<code>save</code>) each document in the process. The approach I'm using looks roughly like:</p>
  
  <pre><code>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()
  </code></pre>
  
  <p><strong>The problem is that <code>save</code> is apparently modifying the order of documents in the cursor.</strong> For example, if my collection is made of 3 documents (<code>id</code>s omitted for clarity):</p>
  
  <pre><code>{
      "name": "one"
  }
  {
      "name": "two"
  }
  {
      "name": "three"
  }
  </code></pre>
  
  <p>the above program outputs:</p>
  
  <pre><code>&gt; updating doc one
  &gt; updating doc two
  &gt; updating doc two
  </code></pre>
  
  <p>If however, the line <code>collection.save(doc)</code> is removed, the output becomes:</p>
  
  <pre><code>&gt; updating doc one
  &gt; updating doc two
  &gt; updating doc three
  </code></pre>
  
  <p>Why is this happening? What is the right way to safely iterate <em>and</em> update documents in a collection?</p>