Lab4-MongoDB Aggregation-vst
Lab4-MongoDB Aggregation-vst
Objectives
Describe simple aggregation operators that process and compute data such as
$sort, $limit, $group, $sum, $min, $max, and $avg
Combine operators to create multi-stage aggregation pipelines
Build aggregation pipelines that draw insights about the data by returning
aggregated values
Using the $limit operator we can limit the number of documents printed in the
output.
This command will print only 2 documents from the marks collection.
use training
db.marks.aggregate([{"$limit":2}])
This command sorts the documents based on field marks in ascending order.
db.marks.aggregate([{"$sort":{"marks":1}}])
This command sort the documents based on field marks in descending order.
db.marks.aggregate([{"$sort":{"marks":-1}}])
db.marks.aggregate([
{"$sort":{"marks":-1}},
{"$limit":2}
])
```
Exercise 5 - Group by
The operator $group by, along with operators like $sum, $avg,
$min, $max, allows us to perform grouping operations.
This aggregation pipeline prints the average marks across all
subjects.
```
db.marks.aggregate([
{
"$group":{
"_id":"$subject",
"average":{"$avg":"$marks"}
}
}
])
The above query is equivalent to the below sql query.
Now let us put together all the operators we have learnt to answer the
question. “Who are the top 2 students by average marks?”
This involves:
finding the average marks per student.
sorting the output based on average marks in descending order.
limiting the output to two documents.
db.marks.aggregate([
{
"$group":{
"_id":"$name",
"average":{"$avg":"$marks"}
}
},
{
"$sort":{"average":-1}
},
{
"$limit":2
}
])
Practice exercises
1. Find the total marks for each student across all subjects.
2. Find the maximum marks scored in each subject.
3. Find the minimum marks scored by each student.
4. Find the top two subjects based on average marks.