Skip to content

Instantly share code, notes, and snippets.

Embed
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 updating_docs.py
# 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:
# https://groups.google.com/forum/?fromgroups=#!topic/mongodb-user/0bCEb7vcUvg
# Brendan has a good explanation of why we need the doesn't exist query
connection = MongoClient("mongodb://localhost", safe=True)
scores = connection.school.scores
# give me records that don't have the added field
query = {'added': {'$exists': False}}
counter = 0
try:
cursor = scores.find(query)
except:
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
connection.disconnect()
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.