TExcelTAD
Home › MongoDB › Aggregation $addFields

Aggregation $addFields

$addFields adds new fields to each document (or overwrites existing ones) and keeps every other field. Its alias $set does exactly the same thing; many people prefer $set because it reads naturally and matches update pipelines.

js
{ $addFields: { newField: <expression>, … } }
{ $set: { newField: <expression>, … } }      // same stage

Adding computed fields

mongosh · try it yourself
print(db.orders.aggregate([
  { $match: { _id: 1008 } },
  { $addFields: {
      units: { $sum: '$items.qty' },
      month: { $dateToString: { format: '%Y-%m', date: '$date' } }
  } }
]).toArray());
[
  {
    _id: 1008,
    customerId: 3,
    date: ISODate('2026-03-28T16:45:00.000Z'),
    status: 'delivered',
    items: [
      { productId: 1, name: 'Espresso Beans', qty: 1, price: 24.5 },
      { productId: 11, name: 'French Press', qty: 1, price: 35 }
    ],
    total: 59.5,
    units: 2,
    month: '2026-03'
  }
]

Compare with $project, where you would have had to list customerId, date, status, items and total to keep them.

Overwriting a field

Giving an existing field name replaces its value. Here every line item gets a lineTotal, by rewriting the items array with $map:

mongosh · try it yourself
print(db.orders.aggregate([
  { $match: { _id: 1007 } },
  { $set: {
      items: {
        $map: {
          input: '$items',
          as: 'it',
          in: { $mergeObjects: ['$it', { lineTotal: { $multiply: ['$it.qty', '$it.price'] } }] }
        }
      }
  } },
  { $project: { items: 1, total: 1 } }
]).toArray());
[
  {
    _id: 1007,
    items: [
      {
        productId: 6,
        name: 'Green Sencha',
        qty: 2,
        price: 12,
        lineTotal: 24
      },
      {
        productId: 19,
        name: 'Salted Pretzels',
        qty: 3,
        price: 3.5,
        lineTotal: 10.5
      }
    ],
    total: 34.5
  }
]

$mergeObjects combines the original item with the new field.

Building on previous stages

Each $addFields stage can use fields computed by an earlier one. That makes long calculations readable, step by step:

mongosh · try it yourself
db.products.aggregate([
  { $match: { category: 'equipment' } },
  { $set: { stockValue: { $multiply: ['$price', '$stock'] } } },
  { $set: { valueBand: { $switch: {
      branches: [
        { case: { $gte: ['$stockValue', 500] }, then: 'high' },
        { case: { $gte: ['$stockValue', 200] }, then: 'medium' }
      ],
      default: 'low'
  } } } },
  { $sort: { stockValue: -1 } }
]).forEach(p => print(p.name.padEnd(20), String(p.stockValue).padStart(5), p.valueBand));
Paper Filters (100)    720 high
Burr Grinder           534 high
Pour-Over Dripper      435 medium
French Press           315 medium
Gooseneck Kettle       236 medium
Milk Frother             0 low

Adding a constant or nested field

Use $literal for values that look like field paths or operators, and dot notation to add a field inside an embedded document:

mongosh · try it yourself
print(db.customers.aggregate([
  { $match: { _id: 6 } },
  { $set: { 'address.region': 'Europe', currency: { $literal: '$CHF' } } },
  { $project: { name: 1, address: 1, currency: 1 } }
]).toArray());
[
  {
    _id: 6,
    name: 'Tim Berners-Lee',
    address: { city: 'Geneva', country: 'Switzerland', region: 'Europe' },
    currency: '$CHF'
  }
]

Without $literal, '$CHF' would be read as the (missing) field CHF.

Removing fields: $unset

The companion stage $unset removes fields: { $unset: ['joined', 'interests'] } is a shorter way to write a $project with zeros.

Test yourself

What is the difference between $addFields and $project?

  1. None
  2. $addFields keeps all existing fields; $project keeps only the ones you list
  3. $project can't compute values
  4. $addFields can't overwrite fields

How do you add a field whose value is the literal string $5 off?

  1. { promo: '$5 off' }
  2. { promo: { $literal: '$5 off' } }
  3. { promo: { $string: '$5 off' } }
  4. It's impossible