M101P: MongoDB for Developers - Chapter 3: Schema Design

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-

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值