$addFields

The `$addFields` stage in the aggregation pipeline is used to add new fields to documents. It can also be used to reset the values of existing fields. This stage is particularly useful when you need to create new fields based on existing data or modify existing fields within your documents.

Syntax

{
  $addFields: {
    <newField1>: <expression1>,
    <newField2>: <expression2>
  }
}

Parameters

newFieldstringrequired

The name of the new field to add or the existing field to modify.

expressionobjectrequired

The expression to compute the value of the field.

Examples

Sample Data

{
  "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4",
  "name": "First Up Consultants | Beverage Shop",
  "staff": {
    "totalStaff": {
      "fullTime": 8,
      "partTime": 20
    }
  },
  "promotionEvents": [
    { "eventName": "Unbeatable Bargain Bash" }
  ]
}

Adding a new field

Add a new field totalDiscountEvents that counts the number of promotion events.

This query adds a computed field using the $size operator.

Query:

db.stores.aggregate([
  {
    $addFields: {
      totalDiscountEvents: { $size: "$store.promotionEvents" }
    }
  }
])

Output:

[
  {
    "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5",
    "store": {
      "name": "Downtown Store",
      "promotionEvents": ["Summer Sale", "Black Friday", "Holiday Deals"]
    },
    "totalDiscountEvents": 3
  }
]

Modifying an existing field

Add a field totalStaffCount that sums up the full-time and part-time staff.

This query creates a new field by adding two existing fields together.

Query:

db.stores.aggregate([
  {
    $addFields: {
      totalStaffCount: {
        $add: ["$store.staff.totalStaff.fullTime", "$store.staff.totalStaff.partTime"]
      }
    }
  }
])

Output:

[
  {
    "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5",
    "store": {
      "name": "Downtown Store",
      "staff": {
        "totalStaff": { "fullTime": 12, "partTime": 8 }
      }
    },
    "totalStaffCount": 20
  }
]

Related