Skip to content

Instantly share code, notes, and snippets.

@ingumsky
Last active August 29, 2015 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ingumsky/a1457a9e09cfd8967e7c to your computer and use it in GitHub Desktop.
Save ingumsky/a1457a9e09cfd8967e7c to your computer and use it in GitHub Desktop.
M101js (MongoDB course for javascript developers)
/*
You'd better find solutions for those assesments yourself to be sure
you understand MongoDB Aggregation Framework properly.
But if you stuck and need some help and clues to guide you
feel free to use the commands below as a reference.
Note that I splitted each and every aggregation stage.
Hopefully it will help you to find why your code is not working as you want.
*/
// hw 5.1
db.posts.aggregate([
{"$unwind": "$comments"},
{"$group": { "_id": "$comments.author", "posts": { $sum: 1 } }},
{"$project": {"_id": 0, "author": "$_id", "posts": 1} },
{"$sort": {"posts": 1}},
]);
// hw 5.2
db.zips.aggregate([
{
$project: {
city: 1, state: 1, pop: 1, zip: "$_id", _id: 0,
}
},
{
$group: {
"_id": {
city: "$city", state: "$state"
},
zips: {
$addToSet: "$zip"
},
pop: {
$sum: "$pop"
}
}
},
{
$match: {
pop: {
$gt: 25000
},
_id.state: {
$in: ['CT', 'NJ']
}
}
},
{
$group: {
_id: null,
population: {
$avg: "$pop"
}
}
},
]);
// hw 5.3
db.grades.aggregate([
{
$unwind: "$scores"
},
{
$match: {
"scores.type": {
$in: ['exam', 'homework']
}
}
},
{
$group: {
"_id": {
"class": "$class_id",
"student": "$student_id",
},
"student_average": {
$avg: "$scores.score",
}
}
},
{
$group: {
"_id": "$_id.class",
"average": {
$avg: "$student_average",
}
}
},
{
$sort: {
"average": -1,
}
}
]);
// hw 5.4
db.zips.aggregate([
{
$project: {
first_char: {
$substr: ["$city", 0, 1]
},
pop: 1,
}
},
{
$match: {
first_char: {
$regex: "[0-9]"
}
}
},
{
$group: {
_id: null,
pop: {
$sum: "$pop"
}
}
}
]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment