✍️

MongoDB Aggregation Functions Explained with Examples for Beginners

MongoDB Aggregation Functions Explained with Examples

MongoDB Aggregation Functions Explained

Complete beginner-friendly guide with examples, practice questions, and solutions.

What is Aggregation in MongoDB?

Aggregation in MongoDB is used to process data and return calculated results. It helps us filter, group, sort, count, and analyze documents from a collection.

In simple words, aggregation is used when we want summarized data from MongoDB. It works like SQL GROUP BY, SUM, AVG, COUNT, and ORDER BY.

MongoDB Aggregation Pipeline

MongoDB uses an aggregation pipeline. In this pipeline, data passes through multiple stages one by one.

db.collection_name.aggregate([
  { stage1 },
  { stage2 },
  { stage3 }
])
Tip: In most cases, use $match first to filter data and improve performance.

Sample Data

db.students.insertMany([
  {
    name: "Harsh",
    course: "BCA",
    marks: 85,
    city: "Delhi"
  },
  {
    name: "Aman",
    course: "BCA",
    marks: 75,
    city: "Mumbai"
  },
  {
    name: "Riya",
    course: "MCA",
    marks: 90,
    city: "Delhi"
  },
  {
    name: "Rahul",
    course: "BTech",
    marks: 70,
    city: "Delhi"
  },
  {
    name: "Sneha",
    course: "MCA",
    marks: 88,
    city: "Pune"
  }
])

Important MongoDB Aggregation Stages

1. $match

The $match stage is used to filter documents.

db.students.aggregate([
  {
    $match: { city: "Delhi" }
  }
])

2. $group

The $group stage is used to group documents by a field.

db.students.aggregate([
  {
    $group: {
      _id: "$course"
    }
  }
])

3. $sum

The $sum operator is used to calculate total values.

db.students.aggregate([
  {
    $group: {
      _id: "$course",
      totalMarks: { $sum: "$marks" }
    }
  }
])

4. $avg

The $avg operator is used to calculate average values.

db.students.aggregate([
  {
    $group: {
      _id: "$course",
      averageMarks: { $avg: "$marks" }
    }
  }
])

5. $max

The $max operator returns the highest value.

db.students.aggregate([
  {
    $group: {
      _id: "$course",
      highestMarks: { $max: "$marks" }
    }
  }
])

6. $min

The $min operator returns the lowest value.

db.students.aggregate([
  {
    $group: {
      _id: "$course",
      lowestMarks: { $min: "$marks" }
    }
  }
])

7. $sort

The $sort stage is used to sort documents.

db.students.aggregate([
  {
    $sort: { marks: -1 }
  }
])

8. $project

The $project stage is used to show or hide selected fields.

db.students.aggregate([
  {
    $project: {
      name: 1,
      marks: 1,
      _id: 0
    }
  }
])

SQL vs MongoDB Aggregation

SQL MongoDB
WHERE $match
GROUP BY $group
ORDER BY $sort
SELECT $project
LIMIT $limit

Real Practical Example

This query filters Delhi students, groups them by course, and calculates average marks.

db.students.aggregate([
  {
    $match: { city: "Delhi" }
  },
  {
    $group: {
      _id: "$course",
      totalStudents: { $sum: 1 },
      averageMarks: { $avg: "$marks" }
    }
  },
  {
    $sort: { averageMarks: -1 }
  }
])

Practice Questions with Solutions

Click on the button to see the answer.

Question 1: Show all students from Delhi.

db.students.aggregate([
  {
    $match: { city: "Delhi" }
  }
])

Question 2: Group students by course.

db.students.aggregate([
  {
    $group: {
      _id: "$course"
    }
  }
])

Question 3: Count total students in each course.

db.students.aggregate([
  {
    $group: {
      _id: "$course",
      totalStudents: { $sum: 1 }
    }
  }
])

Question 4: Find average marks course-wise.

db.students.aggregate([
  {
    $group: {
      _id: "$course",
      averageMarks: { $avg: "$marks" }
    }
  }
])

Question 5: Find highest marks course-wise.

db.students.aggregate([
  {
    $group: {
      _id: "$course",
      highestMarks: { $max: "$marks" }
    }
  }
])

Question 6: Find lowest marks course-wise.

db.students.aggregate([
  {
    $group: {
      _id: "$course",
      lowestMarks: { $min: "$marks" }
    }
  }
])

Question 7: Sort students by marks in descending order.

db.students.aggregate([
  {
    $sort: { marks: -1 }
  }
])

Question 8: Show only name and marks of students.

db.students.aggregate([
  {
    $project: {
      name: 1,
      marks: 1,
      _id: 0
    }
  }
])

Question 9: Show top 3 students by marks.

db.students.aggregate([
  {
    $sort: { marks: -1 }
  },
  {
    $limit: 3
  }
])

Question 10: Create course-wise student name list.

db.students.aggregate([
  {
    $group: {
      _id: "$course",
      students: { $push: "$name" }
    }
  }
])

More Practical Aggregation Questions

Try these questions yourself for better practice.

  • Find all students whose marks are greater than 80.
  • Display total students city-wise using aggregation.
  • Find the course having highest average marks.
  • Create a course-wise student list using $push.
  • Display top 2 students with highest marks.
  • Find total marks of all Delhi students.
  • Count total students in each city.
  • Find average marks of only BCA students.
  • Sort students by marks in ascending order.
  • Find the highest marks scored by students in every course.

Conclusion

MongoDB Aggregation Functions are very useful for filtering, grouping, sorting, and analyzing data. If you want to create reports, dashboards, or analytics features, aggregation is one of the most important MongoDB topics.

FAQs

What is aggregation in MongoDB?

Aggregation is a process used to process documents and return calculated results.

Which stage is used for filtering?

The $match stage is used for filtering documents.

Which stage is used for grouping?

The $group stage is used for grouping documents.

Is aggregation useful for dashboards?

Yes, aggregation is very useful for reports, charts, and dashboards.

❮ Previous Next ❯