Aggregations and filters in MongoDB

1. Filters in MongoDB

Filters are used in queries to select documents that match certain conditions. You generally use find() for this.

Example:

Suppose we have a collection employees:

[
  { "_id": 1, "name": "Alice", "age": 30, "department": "HR", "salary": 5000 },
  { "_id": 2, "name": "Bob", "age": 25, "department": "IT", "salary": 6000 },
  { "_id": 3, "name": "Charlie", "age": 28, "department": "IT", "salary": 7000 },
  { "_id": 4, "name": "David", "age": 35, "department": "Finance", "salary": 8000 }
]

Filter Example:

  • Find all employees in the IT department:
db.employees.find({ department: "IT" })

Result:

[
  { "_id": 2, "name": "Bob", "age": 25, "department": "IT", "salary": 6000 },
  { "_id": 3, "name": "Charlie", "age": 28, "department": "IT", "salary": 7000 }
]
  • Find employees with salary greater than 6000:
db.employees.find({ salary: { $gt: 6000 } })

Result:

[
  { "_id": 3, "name": "Charlie", "age": 28, "department": "IT", "salary": 7000 },
  { "_id": 4, "name": "David", "age": 35, "department": "Finance", "salary": 8000 }
]

2. Aggregations in MongoDB

Aggregation allows you to process data records and return computed results. MongoDB provides the aggregate() function with a pipeline of stages.

Common Stages:

  • $match: Filter documents (like find)
  • $group: Group documents by a field and apply aggregate functions
  • $sort: Sort the results
  • $project: Include/exclude or compute new fields
  • $limit / $skip: Limit or skip results

Aggregation Example 1: Total salary by department

db.employees.aggregate([
  { $group: { _id: "$department", totalSalary: { $sum: "$salary" } } }
])

Result:

[
  { "_id": "HR", "totalSalary": 5000 },
  { "_id": "IT", "totalSalary": 13000 },
  { "_id": "Finance", "totalSalary": 8000 }
]

Explanation:

  • $group groups documents by department.
  • $sum adds the salary for each group.

Aggregation Example 2: Filter + Aggregate

Find total salary for IT employees only:

db.employees.aggregate([
  { $match: { department: "IT" } },   // Filter
  { $group: { _id: "$department", totalSalary: { $sum: "$salary" } } }
])

Result:

[
  { "_id": "IT", "totalSalary": 13000 }
]

Explanation:

  • $match filters documents first.
  • $group calculates the total salary for IT employees.

Aggregation Example 3: Sorting and projecting

Find average salary per department and sort by highest average:

db.employees.aggregate([
  { $group: { _id: "$department", avgSalary: { $avg: "$salary" } } },
  { $sort: { avgSalary: -1 } }
])

Result:

[
  { "_id": "Finance", "avgSalary": 8000 },
  { "_id": "IT", "avgSalary": 6500 },
  { "_id": "HR", "avgSalary": 5000 }
]

✅ Key takeaway:

  • Filters (find) are for simple queries.
  • Aggregations (aggregate) are for advanced computations like sums, averages, grouping, sorting, and filtering together.

Leave a Reply