MongoDB Aggregation Operators


MongoDB Aggregation Operators

MongoDB provides various aggregation operators used in the aggregation pipeline to manipulate and transform data within collections. These operators help in tasks like filtering, grouping, and calculating data in the pipeline. Below is a breakdown of the most commonly used aggregation operators.


1. $sum

The $sum operator sums up numerical values in a group of documents or array elements. It is frequently used in combination with the $group stage to calculate totals.

  • Usage in $group:

    • Example: Calculate the total price of items in orders.
      db.orders.aggregate([ { $group: { _id: null, totalPrice: { $sum: "$item.price" } } } ])
    • This groups all documents and calculates the sum of the price field for each item.
  • Usage in $project:

    • You can also use $sum to add up elements in an array.
      db.orders.aggregate([ { $project: { totalItems: { $sum: "$items.quantity" } } } ])

2. $avg

The $avg operator calculates the average (mean) of numerical values.

  • Usage in $group:

    • Example: Calculate the average order value.
      db.orders.aggregate([ { $group: { _id: "$customerId", averageOrderValue: { $avg: "$orderValue" } } } ])
  • Usage in $project:

    • You can also calculate the average within a single document.
      db.grades.aggregate([ { $project: { averageGrade: { $avg: "$scores" } } } ])

3. $min

The $min operator selects the minimum value within a group of documents or within an array.

  • Usage in $group:

    • Example: Find the earliest order date for each customer.
      db.orders.aggregate([ { $group: { _id: "$customerId", firstOrder: { $min: "$orderDate" } } } ])
  • Usage in $project:

    • It can also be used to find the minimum value in an array.
      db.students.aggregate([ { $project: { lowestScore: { $min: "$testScores" } } } ])

4. $max

The $max operator selects the maximum value within a group of documents or within an array.

  • Usage in $group:

    • Example: Find the highest order value for each customer.
      db.orders.aggregate([ { $group: { _id: "$customerId", maxOrderValue: { $max: "$orderValue" } } } ])
  • Usage in $project:

    • To find the maximum score in an array.
      db.students.aggregate([ { $project: { highestScore: { $max: "$testScores" } } } ])

5. $first

The $first operator returns the first document in each group of documents, based on the order defined in the pipeline.

  • Usage in $group:
    • Example: Find the first order made by each customer.
      db.orders.aggregate([ { $group: { _id: "$customerId", firstOrder: { $first: "$orderDate" } } } ])

6. $last

The $last operator returns the last document in each group of documents, based on the order defined in the pipeline.

  • Usage in $group:
    • Example: Find the last order made by each customer.
      db.orders.aggregate([ { $group: { _id: "$customerId", lastOrder: { $last: "$orderDate" } } } ])

7. $push

The $push operator appends values from each document in a group to an array. It’s often used in combination with $group to collect values into arrays.

  • Usage in $group:
    • Example: Create an array of all orders for each customer.
      db.orders.aggregate([ { $group: { _id: "$customerId", orders: { $push: "$orderValue" } } } ])

8. $addToSet

The $addToSet operator is similar to $push, but it only adds unique values to the array, avoiding duplicates.

  • Usage in $group:
    • Example: Collect unique tags from articles.
      db.articles.aggregate([ { $group: { _id: null, uniqueTags: { $addToSet: "$tags" } } } ])

9. $lookup

The $lookup operator performs a left outer join with another collection.

  • Example: Join orders with customers to get customer details for each order.
    db.orders.aggregate([ { $lookup: { from: "customers", localField: "customerId", foreignField: "_id", as: "customerDetails" } } ])

10. $unwind

The $unwind operator deconstructs an array field from a document into multiple documents, where each document represents a single array element.

  • Example: Unwind the items array in an order.
    db.orders.aggregate([ { $unwind: "$items" } ])

11. $mergeObjects

The $mergeObjects operator combines multiple documents or fields into a single document.

  • Usage: You can merge fields from multiple documents into one.
    db.products.aggregate([ { $group: { _id: "$category", mergedProduct: { $mergeObjects: "$$ROOT" } } } ])

12. $regexMatch

The $regexMatch operator allows filtering documents based on regular expressions.

  • Example: Match documents where the name field starts with “A”.
    db.users.aggregate([ { $match: { name: { $regex: "^A", $options: "i" } } } ])

13. $cond

The $cond operator evaluates a condition and returns one of two values, depending on whether the condition is true or false.

  • Usage: Implement conditional logic in the aggregation pipeline.
    db.sales.aggregate([ { $project: { discount: { $cond: { if: { $gte: ["$totalAmount", 100] }, then: 0.1, else: 0 } } }} ])

14. $expr

The $expr operator allows the use of aggregation expressions within the $match stage.

  • Example: Find documents where orderTotal is greater than minimumOrder value.
    db.orders.aggregate([ { $match: { $expr: { $gt: ["$orderTotal", "$minimumOrder"] } } } ])