Skip to content

Instantly share code, notes, and snippets.

@k0emt
Last active August 14, 2019 20:51
Show Gist options
  • Save k0emt/4694965 to your computer and use it in GitHub Desktop.
Save k0emt/4694965 to your computer and use it in GitHub Desktop.
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