Skip to content

Instantly share code, notes, and snippets.

@cjsaylor
Created December 3, 2012 02:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cjsaylor/4192306 to your computer and use it in GitHub Desktop.
Save cjsaylor/4192306 to your computer and use it in GitHub Desktop.
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
Copy link

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
Copy link

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

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

@vovkvlad
Copy link

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