TExcelTAD
Home › MongoDB › Aggregation $project

Aggregation $project

$project reshapes every document: it chooses which fields to keep, renames them and computes new ones. Its syntax extends the find projection:

Form Meaning
field: 1 keep the field
field: 0 remove the field (exclusion mode)
newName: '$oldField' copy (rename) a field
newName: { <expression> } compute a value
'a.b': 1 or a: { b: 1 } keep a nested field

As in find(), _id is kept unless you write _id: 0, and you can't mix 1s and 0s (apart from _id).

Keep and rename

mongosh · try it yourself
print(db.customers.aggregate([
  { $match: { tier: 'gold' } },
  { $project: { _id: 0, customer: '$name', city: '$address.city', since: '$joined' } }
]).toArray());
[
  {
    customer: 'Ada Lovelace',
    city: 'London',
    since: ISODate('2026-01-04T09:15:00.000Z')
  },
  {
    customer: 'Grace Hopper',
    city: 'New York',
    since: ISODate('2026-01-20T08:00:00.000Z')
  },
  {
    customer: 'Barbara Liskov',
    city: 'Boston',
    since: ISODate('2026-03-09T09:05:00.000Z')
  }
]

city is now a top-level field: the dotted path pulled the value out of the embedded address.

Computing fields

Expressions can do arithmetic, string work, conditionals and much more:

mongosh · try it yourself
db.products.aggregate([
  { $match: { category: 'coffee' } },
  { $project: {
      _id: 0,
      name: 1,
      code: { $toUpper: { $substrCP: ['$name', 0, 3] } },
      priceCents: { $multiply: ['$price', 100] },
      status: { $cond: { if: { $gt: ['$stock', 0] }, then: 'in stock', else: 'sold out' } }
  } }
]).forEach(p => print(p));
{
  name: 'Espresso Beans',
  code: 'ESP',
  priceCents: 2450,
  status: 'in stock'
}
{
  name: 'House Blend',
  code: 'HOU',
  priceCents: 1800,
  status: 'in stock'
}
{
  name: 'Ethiopia Yirgacheffe',
  code: 'ETH',
  priceCents: 2700,
  status: 'in stock'
}
{
  name: 'Colombia Supremo',
  code: 'COL',
  priceCents: 2100,
  status: 'sold out'
}
{
  name: 'Decaf Night Owl',
  code: 'DEC',
  priceCents: 1950,
  status: 'in stock'
}

Common expression operators

Area Operators
Arithmetic $add $subtract $multiply $divide $mod $round $abs
Strings $concat $toUpper $toLower $substrCP $split $strLenCP $trim
Conditionals $cond $ifNull $switch
Comparison $eq $ne $gt $gte $lt $lte $cmp
Arrays $size $filter $map $reduce $in $arrayElemAt $sum $avg
Dates $year $month $dayOfMonth $dateToString $dateDiff
Types $toString $toInt $toDouble $type

Array expressions are especially useful on the embedded items:

mongosh · try it yourself
print(db.orders.aggregate([
  { $match: { _id: { $in: [1005, 1009] } } },
  { $project: {
      products: { $map: { input: '$items', as: 'it', in: '$it.name' } },
      units: { $sum: '$items.qty' },
      bigLines: { $size: { $filter: { input: '$items', as: 'it', cond: { $gte: ['$it.qty', 2] } } } }
  } }
]).toArray());
[
  {
    _id: 1005,
    products: [ 'Pour-Over Dripper', 'Paper Filters (100)', 'House Blend' ],
    units: 4,
    bigLines: 1
  },
  {
    _id: 1009,
    products: [ 'Dark Chocolate Bar', 'Oat Cookies' ],
    units: 8,
    bigLines: 2
  }
]

Inside $map and $filter, '$it' (two dollars) refers to the variable named by as, here the current array element.

Missing values with $ifNull

Three customers have no email. $ifNull substitutes a default:

mongosh · try it yourself
db.customers.aggregate([
  { $match: { _id: { $in: [3, 4, 8] } } },
  { $project: { _id: 0, name: 1, contact: { $ifNull: ['$email', 'no email on file'] } } }
]).forEach(c => print(c.name, '->', c.contact));
Grace Hopper -> grace@example.com
Linus Torvalds -> no email on file
Donald Knuth -> no email on file

Tip: If you want to keep all existing fields and only add a few, use $addFields instead: with $project you would have to list every field you want to keep.

Test yourself

What does { $project: { city: '$address.city' } } produce?

  1. { _id, address: { city } }
  2. { _id, city: <the city> }
  3. { city: '$address.city' } as text
  4. An error

Inside $map: { input: '$items', as: 'it', in: … }, how do you refer to the current element's qty?

  1. '$it.qty'
  2. '$it.qty'
  3. '$items.qty'
  4. 'it.qty'

Which expression returns 'n/a' when phone is missing or null?

  1. { $cond: ['$phone', 'n/a'] }
  2. { $ifNull: ['$phone', 'n/a'] }
  3. { $exists: '$phone' }
  4. { $or: ['$phone', 'n/a'] }