Show List

Aggregation framework for complex queries

The Aggregation Framework in MongoDB is a powerful tool for performing complex queries on collections. It provides a way to group, filter, transform, and analyze data in a collection. Here are some examples of how to use the Aggregation Framework in MongoDB:

  • Grouping data by a field: To group data by a field in a collection, you can use the $group stage of the aggregation pipeline. For example, to group the documents in the "orders" collection by the "product" field and calculate the total sales for each product, you can use the following aggregation pipeline:
php
Copy code
db.orders.aggregate([ { $group: { _id: "$product", total_sales: { $sum: "$price" } } } ])

This will return a list of documents that contain the "_id" field with the product name and the "total_sales" field with the total sales for that product.

  • Filtering data: To filter data in a collection, you can use the $match stage of the aggregation pipeline. For example, to filter the documents in the "orders" collection by the "status" field and only include documents with the status "complete", you can use the following aggregation pipeline:
lua
Copy code
db.orders.aggregate([ { $match: { status: "complete" } } ])

This will return a list of documents that have the status "complete".

  • Sorting data: To sort data in a collection, you can use the $sort stage of the aggregation pipeline. For example, to sort the documents in the "orders" collection by the "date" field in descending order, you can use the following aggregation pipeline:
bash
Copy code
db.orders.aggregate([ { $sort: { date: -1 } } ])

This will return a list of documents that are sorted by the "date" field in descending order.

  • Projecting data: To project only specific fields from the documents in a collection, you can use the $project stage of the aggregation pipeline. For example, to project only the "name" and "age" fields from the documents in the "customers" collection, you can use the following aggregation pipeline:
php
Copy code
db.customers.aggregate([ { $project: { name: 1, age: 1 } } ])

This will return a list of documents that only contain the "name" and "age" fields.

These are just a few examples of the many capabilities of the Aggregation Framework in MongoDB. It can be used for more complex operations like filtering by date range, joining collections, and more.


    Leave a Comment


  • captcha text