Search code examples
pythonmongodbpymongoupdating

Updating each element in collection MongoDB


I am trying to update each element of a collection, one at a time. My pseudocode is:

for e in myColl.find():
    # ...calculations involving variables of 'e'
    myColl.update({'_id':e['_id']}, { '$set': {'myvar':123}})

where myvar is a new variable added to e.

This update results in no change at all in the collection.

I imagine it is because the cursor is already looping through myColl and therefore cannot update inside the collection, but I don't know how to get around it.

Any ideas?


Solution

  • for row in myColl.find():
        row['myvar'] = 123
        myColl.save(row)