Skip to content

Instantly share code, notes, and snippets.

@cjsaylor

cjsaylor/5.1.js

Created Dec 3, 2012
Embed
What would you like to do?
m101 - Mongo HW 5
db.posts.aggregate( [ { $project : { 'comments.author': 1 } }, { $unwind : "$comments" }, { $group : { _id : { comments : "$comments" }, n : { $sum : 1 } } }, { $sort: {"n": -1} } ] )
db.zips.aggregate([
{
"$match": {
state: {"$in": ["CA", "NY"]}
}
},
{
"$group": {
"_id": {"state": "$state", "city": "$city"},
tPop: {"$sum": "$pop" }
}
},
{
"$match": {
"tPop": { "$gt": 25000 }
}
},
{
"$group": {
_id: "$state",
average: {"$avg": "$tPop"}
}
}
])
db.grades.aggregate([
{
"$match": {
"scores.type": {
"$in": ["exam", "homework"]
}
}
},
{
"$unwind": "$scores"
},
{
"$group": {
_id: {"student_id": "$student_id", "class_id": "$class_id"},
sGPA: {"$avg": "$scores.score"}
}
},
{
"$group": {
_id: {"class_id": "$_id.class_id"},
cGPA: {"$avg": "$sGPA"}
}
},
{
"$sort": {
cGPA: -1
}
}
])
db.zips.aggregate([
{
"$project": {
"fc": {"$substr": ["$city", 0, 1]},
"city": 1,
"pop": 1
}
},
{
"$match": {
"fc": {"$in": ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]}
}
},
{
"$group": {
_id: null,
pop: {"$sum": "$pop"}
}
}
])
@mcloide

This comment has been minimized.

Copy link

@mcloide mcloide commented Dec 5, 2012

5.3.js change:

db.grades.aggregate([
{
"$unwind": "$scores"
},
{
"$match": {
"scores.type": {
"$in": ["exam", "homework"]
}
}
},
{
"$group": {
_id: {"student_id": "$student_id", "class_id": "$class_id"},
sGPA: {"$avg": "$scores.score"}
}
},
{
"$group": {
_id: {"class_id": "$_id.class_id"},
cGPA: {"$avg": "$sGPA"}
}
}
,
{"$sort":{cGPA:-1}}
])

Have to unwind the scores prior so you can correctly match the exam.

@marcoberri

This comment has been minimized.

Copy link

@marcoberri marcoberri commented May 3, 2013

5.2
the last $group using "$_id.state"

{"$group":{"_id":"$_id.state",average:{"$avg":"$tPop"}}}

@vovkvlad

This comment has been minimized.

Copy link

@vovkvlad vovkvlad commented Sep 8, 2015

@marcoberri, I know that it's been two year since your comment, but actually it is not important which _id to use in the last group, if you write _id: null the answer will be the same

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.