ITP249 - Lecture - 13 - v2-2
ITP249 - Lecture - 13 - v2-2
ITP249 - Lecture - 13 - v2-2
Aggregation Framework
ITP 249
Topics
• MongoDB Aggregation Framework
– Match
– Project
– Group
– Match
– Sort
– Limit
– And many more
Recall: SELECT
SELECT … *
FROM …
WHERE …
GROUP BY…
HAVING …
ORDER BY …
LIMIT …
Conversion to MongoDB
SELECT CLAUSE MONGODB
WHERE Match
SELECT Project
GROUP BY Group
HAVING Match
ORDER BY Sort
// Pipeline
[
// Stage 1
{
$match: {
state: "AZ"
}
},
// Stage 2
{
$group: {
_id: "$postal_code",
numberofbiz: {$sum: 1}
}
},
// Stage 3
{
$sort: {
numberofbiz: -1
}
},
],
On your own - #1
• Limit the results to the top 5 postal codes
• Only show postal codes with more than
1000 businesses
On your own - #2
• Show the business with the most
categories
– $project (field1:1, field2:1….
– $size
Summary
• We explored aggregation using Mongo
db.restarurants.aggregate({$project: {name: 1,
totalscore: {$add:
["$field1",
"$field2",
"$field3",
"$field4",
"$field4”
]}}},
{$sort:{totalscore:-1}},
{$limit:1})