M101P: MongoDB for Developers - Chapter 2: CRUD

Homework 2.1

> db.grades.find({score:{$gte:65}}).sort({score:1})
{ "_id" : ObjectId("xxx"), "student_id" : 22, "type" : "exam", "score" : 65.02518811936324 }
{ "_id" : ObjectId("yyy"), "student_id" : 100, "type" : "homework", "score" : 65.29214756759019 }
{ "_id" : ObjectId("zzz"), "student_id" : 63, "type" : "homework", "score" : 65.31038121884853 }
{ "_id" : ObjectId("aaa"), "student_id" : 128, "type" : "homework", "score" : 65.47002803265133 }

22

Homework 2.2

$ cat hw2.2.py

# Andrew Erlichson
# MongoDB, Inc.
# M101P - Copyright 2015, All Rights Reserved


import pymongo
import datetime
import sys

# establish a connection to the database
connection = pymongo.MongoClient("mongodb://localhost")

# removes one student
def remove_sid_score(student_id, score):
    db=connection.students
    scores = db.grades
    try:
        result = scores.delete_one({'student_id':student_id,'score':score})
        print "num removed: ", result.deleted_count
    except Exception as e:
        print "Exception: ", type(e), e

def remove_id(id):
    db=connection.students
    scores = db.grades
    try:
        result = scores.delete_one({'_id':id})
        print "num removed: ", result.deleted_count
    except Exception as e:
        print "Exception: ", type(e), e

def remove1():
    db=connection.students
    scores = db.grades

    print "Searching for student min score"
    pipeline = [ {"$group": {"_id": "$student_id", "score": {"$min": "$score"}}} ]
    try:
        docs = scores.aggregate(pipeline)
        for doc in docs:
            print doc['_id'],doc['score']
            remove_sid_score(doc['_id'], doc['score'])

    except Exception as e:
        print "Exception: ", type(e), e


def remove2():
    db=connection.students
    scores=db.grades
    docs = scores.find().sort([ ('student_id',pymongo.ASCENDING),('score',pymongo.ASCENDING)])
    sid = ""
    for doc in docs:
        if doc['student_id'] != sid:
            print doc
            remove_id(doc['_id'])
            sid = doc['student_id']

#remove1()
remove2()



> use students
switched to db students
> db.grades.count()
600
> db.grades.find().sort( { 'score' : -1 } ).skip( 100 ).limit( 1 )
{ "_id" : ObjectId("50906d7fa3c412bb040eb84b"), "student_id" : 181, "type" : "exam", "score" : 89.10554845143109 }
> db.grades.find( { }, { 'student_id' : 1, 'type' : 1, 'score' : 1, '_id' : 0 } ).sort( { 'student_id' : 1, 'score' : 1, } ).limit( 5 )
{ "student_id" : 0, "type" : "quiz", "score" : 31.95004496742112 }
{ "student_id" : 0, "type" : "exam", "score" : 54.6535436362647 }
{ "student_id" : 0, "type" : "homework", "score" : 63.98402553675503 }
{ "student_id" : 1, "type" : "homework", "score" : 44.31667452616328 }
{ "student_id" : 1, "type" : "exam", "score" : 74.20010837299897 }
>
> db.grades.aggregate( { '$group' : { '_id' : '$student_id', 'average' : { $avg : '$score' } } }, { '$sort' : { 'average' : -1 } }, { '$limit' : 1 } )
{ "_id" : 54, "average" : 96.19488173037341 }

54

Homework 2.3

$ vi userDAO.py

            # XXX HW 2.3 Students Work Here
            # you will need to retrieve right document from the users collection.
            print "This space intentionally left blank."
            user = self.users.find_one({'_id':username})


...


            # XXX HW 2.3 Students work here
            # You need to insert the user into the users collection.
            # Don't over think this one, it's a straight forward insert.
            self.users.insert(user)
            print "This space intentionally left blank."




$ python validate.py
Welcome to the HW 2.3 validation tester
Trying to create a test user  KwIrUZf
Found the test user  KwIrUZf  in the users collection
User creation successful.
Trying to login for test user  KwIrUZf
User login successful.
Validation Code is  jkfds5834j98fnm39njf0920f02

jkfds5834j98fnm39njf0920f02

Homework 2.4

mongorestore -d video


> db.movieDetails.find({rated:"PG-13",year:2013,"awards.wins":0})
{ "_id" : ObjectId("5692a3e124de1e0ce2dfda22"), "title" : "A Decade of Decadence, Pt. 2: Legacy of Dreams", "year" : 2013, "rated" : "PG-13", "released" : ISODate("2013-09-13T04:00:00Z"), "runtime" : 65, "countries" : [ "USA" ], "genres" : [ "Documentary" ], "director" : "Drew Glick", "writers" : [ "Drew Glick" ], "actors" : [ "Gordon Auld", "Howie Boulware Jr.", "Tod Boulware", "Chen Drachman" ], "plot" : "A behind the scenes look at the making of A Tiger in the Dark: The Decadence Saga.", "poster" : null, "imdb" : { "id" : "tt2199902", "rating" : 8, "votes" : 50 }, "awards" : { "wins" : 0, "nominations" : 0, "text" : "" }, "type" : "movie" }

A Decade of Decadence, Pt. 2: Legacy of Dreams

Homework 2.5

> db.movieDetails.count({"countries.1":"Sweden"})
6

6

-eof-

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值