Aggregate Query

In MongoDB, the aggregate method is used to perform complex data processing operations and return the computed results. It allows us to apply multiple operations on a collection, like filtering, grouping, sorting, and transforming the data. The aggregate function takes an array of stages as its argument, and each stage describes a specific operation to be performed on the input documents.

Example:

db.sales.aggregate(
   [
      {
         $match: {
            date: { $gte: ISODate("2022-01-01") }
         }
      },
      {
         $group: {
            _id: "$product",
            total_sales: { $sum: "$quantity" }
         }
      },
      {
         $sort: { total_sales: -1 }
      },
      {
         $limit: 5
      }
   ]
)

This query first filters the collection to only include documents with a date field greater than or equal to January 1, 2022. Then, it groups the documents by the product field, and calculates the sum of the quantity field for each group. Next, it sorts the results by the total_sales field in descending order, and limits the output to the top 5 results.

Here are some of the most commonly used stages in the aggregate method:

  • $match: filters documents based on a specified condition.

  • $group: groups documents by a specified field and calculates an aggregate value for each group.

  • $project: selects and transforms fields from the input documents.

  • $sort: sorts the output documents based on a specified field.

  • $limit: limits the number of output documents.

  • $skip: skips a specified number of documents from the output.

  • $unwind: deconstructs an array field from the input documents and outputs one document for each element in the array.

Aggregate queries are very powerful and can be used to perform complex data processing operations on large amounts of data. However, they can also be resource-intensive and may require careful optimization to ensure efficient execution.

Last updated