Homework 3.1
$ cat r.py
import pymongo
import sys
connection = pymongo.MongoClient("mongodb://localhost")
db=connection.school
students=db.students
docs = students.find({'scores.type':'homework'})
for doc in docs:
min_score = min([ s['score'] for s in doc['scores'] if s['type']=='homework'])
new_scores = [ s for s in doc['scores'] if s['type']!='homework' or s['type']=='homework' and s['score']!=min_score ]
students.update({"_id":doc['_id']}, {"$set":{"scores":new_scores}})
> use school
switched to db school
> db.students.aggregate( [
... { '$unwind': '$scores' },
... {
... '$group':
... {
... '_id': '$_id',
... 'average': { $avg: '$scores.score' }
... }
... },
... { '$sort': { 'average' : -1 } },
... { '$limit': 1 } ] )
{ "_id" : 13, "average" : 91.98315917172745 }
13
Homework 3.2
$ vi blogPostDAO.py
# XXX HW 3.2 Work Here to insert the post
print "Inserting the post"
result = self.posts.insert_one(post)
...
# XXX HW 3.2 Work here to get the posts
cursor = self.posts.find().sort([('date',pymongo.DESCENDING)]).limit(num_posts)
...
# XXX 3.2 Work here to retrieve the specified post
post = self.posts.find_one({'permalink':permalink})
$ python validate.py
Welcome to the HW 3.2 and HW 3.3 validation tester
Trying to create a test user uNcDQVm
Found the test user uNcDQVm in the users collection
User creation successful.
Trying to login for test user uNcDQVm
User login successful.
Trying to submit a post with title cPsdVEDhKXcGKnORNpjMuzqJFbkEIS
Submission of single post successful
Trying to submit a post with title BhHwoBlDPZEhWPsrFaPxlhcPUXrsUh
Submission of second post successful
Trying to grab the blog home page at url http://localhost:8082/
Block index looks good.
Found blog post in posts collection
Tests Passed for HW 3.2. Your HW 3.2 validation code is 89jklfsjrlk209jfks2j2ek
Trying to submit a blog comment for post with title cPsdVEDhKXcGKnORNpjMuzqJFbkEIS
Successfully added blog comments
Tests Passed for HW 3.3. Your HW 3.3 validation code is jk1310vn2lkv0j2kf0jkfs
89jklfsjrlk209jfks2j2ek
Homework 3.3
$ vi blogPostDAO.py
# XXX HW 3.3 Work here to add the comment to the designated post. When done, modify the line below to return the number of documents updated by your modification, rather than just -1.
result = self.posts.update_one({'permalink':permalink},{'$addToSet':{'comments':comment}})
return result.modified_count
#return -1 # Change this to return the number of documents updated by the code for HW 3.3
jk1310vn2lkv0j2kf0jkfs
-eof-