MongoDB Aggregation Tutorial

MongoDB Aggregation commonly used for tasks such as filtering, grouping, sorting, and reshaping data within a MongoDB collection.

Aggregate Data

The MongoDB aggregate method to perform data aggregation in MongoDB.

db.collection.aggregate(pipeline);
        

Stages in Aggregation

Aggregation pipelines consist of multiple stages, each with a specific operation.

db.sales.aggregate([
    { $match: { date: { $gte: ISODate("2022-01-01") } } },
    { $group: { _id: "$product", total: { $sum: "$quantity" } } }
  ]);
        

$match Stage

Filters documents that meet specific criteria.

{ $match: { category: "Electronics" } }
        

$group Stage

Groups documents based on a specified key and performs aggregate operations.

{ $group: { _id: "$city", totalSales: { $sum: "$sales" } } }

$project Stage

Reshapes documents, including selecting fields and creating new ones.

{ $project: { name: 1, totalSales: "$sales" } }
        

$sort Stage

Sorts documents based on specified fields.

{ $sort: { totalSales: -1 } } // Descending order
        

$limit Stage

Limits the number of documents in the result.

{ $limit: 10 }
        

$skip Stage

Skips a specified number of documents in the result.

{ $skip: 5 }
        

$unwind Stage

Deconstructs arrays, creating a separate document for each element.

{ $unwind: "$tags" }

$lookup Stage

Performs a left outer join with another collection.

{
  $lookup: {
    from: "orders",
    localField: "order_id",
    foreignField: "_id",
    as: "orderDetails"
  }
} 

$out Stage

Writes the results of the aggregation to a new collection.

{ $out: "newCollection" }
        

Aggregation Operators

The aggregation operators like $sum, $avg, $max, and $min within the $group stage for calculations.

{ $group: { _id: "$category", maxPrice: { $max: "$price" } } }