Skip to content

Instantly share code, notes, and snippets.

@KalikaKay
Last active June 13, 2016 13:10
Show Gist options
  • Save KalikaKay/40b1dc7435dcdcee3f0b6f171e4d0d89 to your computer and use it in GitHub Desktop.
Save KalikaKay/40b1dc7435dcdcee3f0b6f171e4d0d89 to your computer and use it in GitHub Desktop.
PyCharming
import pymongo
import sys
# Connect
connection = pymongo.MongoClient("mongodb://localhost")
# Fondle
db = connection.school
grades = db.school.students
## Feeling a little loopy today. Looking at this problem I was given.
## Remove lowest items from a mongodb database.
# I'm in the mood to unwind.
# I need a unique student_id and the lowest grade. So, for example, I need all student_id 9.
# Now I know data can also get the lowest here, but I don't know... do I want the lowest grade with this function?
# Or do I just want the student? Hrm...
# To hell with it - we'll get the lowest value here.
def lowest_grade(student_id, score):
query = {"_id": student_id, "scores": score}
# Jeez. Nothing's simple with me.
print "Searchin' query: %s" % query
try:
cursor = grades.find(query)
#cursor = cursor.limit(1)
#cursor = cursor.sort([('scores.score', pymongo.ASCENDING)])
except Exception as e:
print "Unexpected error:", type(e), e
for doc in cursor:
print doc, ' ', id
# Iterate through the students and print their ids or whatever.
def sort_the_students(type):
query = {"name" : "Bao Ziglar"}
#I am so grateful for the unwind function. Nothing like a nice bottle of whine during an aggregation lesson.
# Jeez. Nothing's simple with me.
#print "Searchin' query: %s" % query
try:
cursor = db.students.aggregate([ {'$unwind': '$scores'} ] )
#print cursor.next()
investing_id = db.students.aggregate([ {'$unwind': '$scores'} ] ).next()['_id']
count = 0
score = db.students.aggregate([ {'$unwind': '$scores'} ] ).next()['scores']['score']
#print investing_id , " ", scorey
selected = "null"
scores = []
except Exception as e:
print "Expected error:", type(e), e
for doc in cursor:
if doc['scores']['type'] == 'homework':
if investing_id == doc['_id']:
if count != 0:
homework = doc['scores']
#print "kalika:", score, doc['scores']['score'], doc['_id']
#if doc['scores']['score'] < score:
if doc['scores']['score'] > score:
selected = doc['scores']['score']
else:
selected = score
#print "kalika:", selected, doc['_id']
homework['score'] = selected
homework['type'] = "homework"
#if doc['scores']['score'] == selected:
#print doc
#doc.explain()
# homework = doc['scores']
#else:
#print "kalika:", selected, doc['_id']
# homework = doc['scores']
# homework['score'] = selected
#delete one document from students.scores where homework docid = doc_id, type = homework, and score = selected.
#lowest_grade(doc['_id'], selected)
#print investing_id , ": " , homework
scores.append(homework)
print scores , " ID ", doc['_id']
#print db.students.find_one({ "_id" : doc['_id']})
results = db.students.update({"_id": doc['_id']}, { "$set" : { "scores" : scores}})
print results
scores = []
#Set the score with the selected value to 0, make sure that type = homework.
#query = {"_id" : doc['_id'] }
#consider adding index to scores documents.
#print db.students.find( {"_id": doc['_id']}, { "scores" : { "$elemMatch" : { "score" : selected, type: "homework" } } } )
#print db.students.aggregate( [ { "$match": { "_id" :doc['_id'], "scores": { "$elemMatch": { "score" : selected, "type": "homework" } } } } ] ).next()
#db.students.aggregate([{ $match: {_id: 0, scores: {$elemMatch: {score: 35.8740349954354, type: "homework"}}}}, { $redact: "$PRUNE"}] ).next()
#db.students.aggregate( [ { $match: { _id:0, scores: {$elemMatch: { score : 35.8740349954354, type: "homework" } } } }, { $redact: { $cond: { if: { $eq: ["$type", "homework"] }, then: "$$PRUNE", else: "$$DESCEND" } } } ] )
#db.students.aggregate([{ $match: {_id: 0, scores: {$elemMatch: {score: 35.8740349954354, type: "homework"}}}}, { $redact: { $cond: { if: { $eq: ["$type", "homework"]}, then: "$$KEEP", else: "$$DESCEND"}}}] )
# db.students.aggregate( [ { $match: { _id:0, scores: {$elemMatch: { score : 35.8740349954354, type: "homework" } } } }, { $redact: { $cond: { if: { $gt: [ { $size: { $setIntersection: [ "$type", ["homework"]] } }, 0 ] }, then: "$$KEEP", else: "$$DESCEND" } } } ] )
# db.students.aggregate([{ $match: {_id: 0, scores: {$elemMatch: {score: 35.8740349954354, type: "homework"}}}}, { $redact: { $cond: { if: { $gt: [{ $spot: { $setIntersection: ["$type", ["homework"]]}}, 0]}, then: "$$KEEP", else: "$$DESCEND"}}}] )
#db.students.aggregate( [ { $match: { _id:0, scores: {$elemMatch: { score : 35.8740349954354, type: "homework" } } } }, { $redact: { $cond: { if: { $gt: [ { spot: { $setIntersection: [ "$type", ["homework"] ] } }, 0 ] }, then: "$$KEEP", else: "$$DESCEND" } } } ] )
#db.students.aggregate([ {'$unwind': '$scores'}, {$sort: {scores:{ $meta: "type" } } } ] )
#Can use this one, there's more than one of each type of score.
#db.students.aggregate([{ $match: {_id: 0, scores: {$elemMatch: {score: 35.8740349954354}}}}, { $redact: { $cond: { if: { $eq: ["$type","homework"]}, then: "$$PRUNE", else: "$$DESCEND"}}}] )
count = count + 1
else:
count = count + 1
#if doc['scores']['score'] <= score:
if doc['scores']['score'] >= score:
score = doc['scores']['score']
#print "Selected: ", doc
else:
#score = 760
score = doc['scores']['score']
#print doc['_id'] , " ", scores
#scores = []
#goodbye = grades.delete_one({'_id': doc['_id']})
#$result = db.schoo
#db.collection.update( {_id:doc['id']}, {$set: { scores: scores} } )
#print scores
#print goodbye
#count = count + 1
investing_id = doc['_id']
#print doc["scores"]
else:
#print doc
scores.append(doc['scores'])
#scores.append["3"]
#investing_id = doc['_id']
#print "Scores: ", scores
print count - 1
sort_the_students("homework")
#replace_the_scores(scores)
#lowest_grade(199, { "type" : "homework", "score" : 5.861613903793295 })
@KalikaKay
Copy link
Author

Gist example.

Working with Python and Mongo; aka PyMongo and committing to memory: how to connect to a database, how to aggregate and how to unwind.

Especially useful for understanding the cursor.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment