Last active
August 14, 2019 20:51
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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