querydrill

Learn ›Aggregation ›Arrays in a pipeline

Worked example: revenue per product

$group$match$multiply$set$sum$unwind

One question, worked end to end: how much revenue did each product bring in? Every stage here has appeared already - this is about assembling them in order and checking the document shape as it changes.

Question:

Find total revenue generated by each product.

Our data:

Laptop
price: 1000
quantity: 1

Mouse
price: 50
quantity: 2

Revenue:

price × quantity

Pipeline:

db.orders.aggregate([
  {
    $match: {
      status: "completed"
    }
  },

  {
    $unwind: "$items"
  },

  {
    $group: {
      _id: "$items.product",

      revenue: {
        $sum: {
          $multiply: [
            "$items.price",
            "$items.quantity"
          ]
        }
      }
    }
  }
])

Result:

Laptop → 2000
Mouse → 100
Keyboard → 100

Notice something important:

You don’t always need:

$set
↓
$group

You could do:

$sum: {
  $multiply: [...]
}

directly inside $group.

But sometimes using $set makes a complicated pipeline easier to understand.

Practise this

1 exercise