Search⌘ K
AI Features

Solution: Multi-Stages Aggregation

We'll cover the following...
Query
db.orders.aggregate([
{
$match: {
orderDate: {
$gte: ISODate("2025-01-01T00:00:00Z"),
$lt: ISODate("2026-01-01T00:00:00Z")
}
}
},
{
$group: {
_id: "$customerId",
totalRevenue: { $sum: "$total" },
orderCount: { $sum: 1 }
}
},
{
$match: {
totalRevenue: { $gt: 0 }
}
}
])

The explanation of the query is given below:

  • Line 1: This starts the aggregation pipeline on the orders collection. The aggregate() method processes documents through multiple stages to transform and analyze data.

  • Lines 3–6: $match

    • Filters the documents to include only orders placed in the year 2025.

    • $gte (greater than or equal to) selects orders on or after January 1, 2025.

    • $lt (less than) selects orders before January 1, 2026.

    • Together, they ...