Skip to content

Instantly share code, notes, and snippets.

@cjsaylor
Created December 3, 2012 02:53
Show Gist options
  • 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"}
}
}
])
@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