querydrill

Learn ›Aggregation ›The aggregation pipeline

$set and $addFields

$multiply$project$set

$addFields and $set are the same stage - MongoDB added $set as an alias later. Both add or overwrite fields and leave the rest of the document alone, which is what separates them from $project.

Example:

{
  $set: {
    total: {
      $multiply: [
        "$price",
        "$quantity"
      ]
    }
  }
}

Input:

{
  product: "Laptop",
  price: 1000,
  quantity: 2
}

Output:

{
  product: "Laptop",
  price: 1000,
  quantity: 2,
  total: 2000
}

Whereas $project can reshape what fields remain.

A useful mental model:

$project
→ "What should the output look like?"

$set / $addFields
→ "Add or modify this field"

Try it

$unwind first so there is a single price and quantity to multiply:

db.orders.aggregate([
  { $unwind: "$items" },
  {
    $set: {
      total: {
        $multiply: ["$items.price", "$items.quantity"]
      }
    }
  },
  { $limit: 3 }
])

Notice what is still in the output: everything. $set added a field and touched nothing else. Swap it for $project and you have to list every field you want to keep.