Created
November 30, 2012 19:48
-
-
Save mrmarcondes/4178101 to your computer and use it in GitHub Desktop.
10gen: M101 MongoDB for Developers - Homework 5.1 - 5.4
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// homework 5.1 | |
db.posts.aggregate([ | |
{$project: {"_id": 0, | |
"comments.author": 1 | |
}}, | |
{$unwind: "$comments"}, | |
{$group: {"_id": "$comments.author", | |
sum: {"$sum": 1} | |
}}, | |
{$sort: {"sum": -1}}, | |
]) | |
// homework 5.2 | |
db.zips.aggregate([ | |
{$group:{ | |
"_id": {state: "$state", | |
city: "$city"}, | |
pop: {"$sum": "$pop"} | |
}}, | |
{$match:{"pop":{"$gt":25000}, "_id.state": {"$in": ["CA", "NY"]}}}, | |
{$group:{ | |
"_id":null, | |
avg: {"$avg": "$pop"} | |
}} | |
]) | |
// homework 5.3 | |
db.grades.aggregate([ | |
{$unwind:"$scores"}, | |
{$match:{"scores.type":{"$ne": "quiz"}}}, | |
{$group:{"_id": {class_id: "$class_id", | |
student_id: "$student_id"}, | |
avg_per_student: {"$avg": "$scores.score"} | |
}}, | |
{$group:{ | |
"_id": "$_id.class_id", | |
avg: {"$avg": "$avg_per_student"} | |
}}, | |
{$sort: {"avg": -1}} | |
]) | |
// homework 5.4 | |
db.zips.aggregate([ | |
{$project: | |
{ | |
first_char: {$substr : ["$city",0,1]}, | |
pop:1 | |
}}, | |
{$match:{"first_char":{"$regex": "[0-9]"}}}, | |
{$group:{ | |
"_id":null, | |
sum: {"$sum": "$pop"} | |
}} | |
]) | |
5.4 :: Latest answer is : 76394871
db.zips.aggregate([
{ $project: { _id: 0, city: 1, pop: 1 } },
{ $match: { city: /^(B|D|O|G|N|M).*/ } },
{ $group: { _id: null, pop: { $sum: "$pop" } } },
{ $sort: { city: 1} }
])
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi all, about exercise homework 5.2;
I have a other answer maybe enhance a little performance and I want to share it for everybody
db.zips.aggregate([
{$match:{$or: [{"state":{$eq:"CA"}},{"state":{$eq:"NY"}}]}},
{$group:{_id:{"state":"$state","city":"$city"},sum:{$sum:"$pop"}}},
{$match:{"sum":{$gte:25000}}},
{$group:{_id:null,avgPop:{$avg:"$sum"}}}
])