Aggregation in MongoDB Examples For Lab
Aggregation in MongoDB Examples For Lab
db.students.insertMany([
{ _id: 3, name: "Charlie", age: 21, score: 78 },
{ _id: 4, name: "David", age: 23, score: 88 },
{ _id: 5, name: "Emma", age: 20, score: 95 },
{ _id: 6, name: "Frank", age: 22, score: 75 },
{ _id: 7, name: "Grace", age: 21, score: 90 },
{ _id: 8, name: "Hannah", age: 22, score: 82 },
{ _id: 9, name: "Ivy", age: 20, score: 89 },
{ _id: 10, name: "Jack", age: 23, score: 91 },
{ _id: 11, name: "Katherine", age: 21, score: 87 },
{ _id: 12, name: "Leo", age: 22, score: 79 },
// Add more student documents here...
]);
-----------------------------------------------------------------------------------
-------
// $match
db.students.aggregate([
{
$match: { age: { $gte: 21 } }
}
]);
db.students.aggregate([
{
$group: {
_id: "$age", // Group by the "age" field
count: { $sum: 1 } // Count the number of students in each age group
}
}
]);
Example 2: Find Maximum and Minimum Scores by Age Group
db.students.aggregate([
{
$group: {
_id: "$age", // Group by the "age" field
maxScore: { $max: "$score" }, // Find the maximum score in each age group
minScore: { $min: "$score" } // Find the minimum score in each age group
}
}
]);
Example 3: Calculate Total Score and Average Score for Each Age Group
db.students.aggregate([
{
$group: {
_id: "$age", // Group by the "age" field
totalScore: { $sum: "$score" }, // Calculate the total score in each age
group
averageScore: { $avg: "$score" } // Calculate the average score in each age
group
}
}
]);
Example 4: Find the Most Common Age Among Students
db.students.aggregate([
{
$group: {
_id: "$age", // Group by the "age" field
count: { $sum: 1 } // Count the number of students in each age group
}
},
{
$sort: { count: -1 } // Sort the results by count in descending order
},
{
$limit: 1 // Limit the result to the top age group with the most
students
}
]);
-----------------------------------------------------------------------------------
-------
$sort
Example 1: Sort Documents by a Single Field in Ascending Order
db.students.aggregate([
{
$sort: { name: 1 }
}
]);
Example 2: Sort Documents by a Single Field in Descending Order
db.students.aggregate([
{
$sort: { age: -1 }
}
]);
Example 3: Sort Documents by Multiple Fields
db.students.aggregate([
{
$sort: { age: 1, score: -1 }
}
]);