Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
This gist shows how to loop throw and alter/update an individual uniquely identified document.
from pymongo import MongoClient
import sys
# code example to show updating individual records in a loop
# initialize the database with:
# mongoimport -d school -c scores --type json grades.js
# verify no records with "added"
# db.scores.find({"added":{$exists:true}}) // returns nothing
# run this program
# python
# use the command below in the mongo shell to see the records that were altered:
# use school
# db.scores.find({"added":{$exists:true}})
# db.scores.find({"added":{$exists:true}}).count() // should be 800
# in the series of posts here:
# Brendan has a good explanation of why we need the doesn't exist query
connection = MongoClient("mongodb://localhost", safe=True)
scores =
# give me records that don't have the added field
query = {'added': {'$exists': False}}
counter = 0
cursor = scores.find(query)
print("Unexpected error:", sys.exc_info()[0])
for doc in cursor:
counter += 1
doc['added'] = counter
scores.update({"_id": doc['_id']}, {'$set': {'added': counter}})
print counter
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.