0
0
MongoDBquery~5 mins

$addFields for computed fields in MongoDB

Choose your learning style9 modes available
Introduction

$addFields lets you add new fields or change existing ones in your data by calculating values. It helps you create extra information without changing the original data.

You want to add a new field that shows the total price by multiplying quantity and price per item.
You need to create a full name field by joining first and last names.
You want to add a field that shows if a user is an adult based on their age.
You want to calculate a discount price based on the original price and discount rate.
Syntax
MongoDB
db.collection.aggregate([
  {
    $addFields: {
      newField1: <expression>,
      newField2: <expression>
    }
  }
])

The $addFields stage is used inside an aggregation pipeline.

You can add multiple fields at once by listing them inside the $addFields object.

Examples
Adds a new field totalPrice by multiplying quantity and price.
MongoDB
db.orders.aggregate([
  {
    $addFields: {
      totalPrice: { $multiply: ["$quantity", "$price"] }
    }
  }
])
Creates a fullName field by joining first and last names with a space.
MongoDB
db.users.aggregate([
  {
    $addFields: {
      fullName: { $concat: ["$firstName", " ", "$lastName"] }
    }
  }
])
Adds a boolean isAdult field that is true if age is 18 or more.
MongoDB
db.people.aggregate([
  {
    $addFields: {
      isAdult: { $gte: ["$age", 18] }
    }
  }
])
Sample Program

This query adds two new fields: totalCost which is units sold times unit price, and discountPrice which applies a 10% discount to the unit price before multiplying by units sold.

MongoDB
db.sales.aggregate([
  {
    $addFields: {
      totalCost: { $multiply: ["$unitsSold", "$unitPrice"] },
      discountPrice: { $multiply: ["$unitsSold", { $multiply: ["$unitPrice", 0.9] }] }
    }
  }
])
OutputSuccess
Important Notes

If the field already exists, $addFields will overwrite it with the new value.

You can use any valid MongoDB expression inside $addFields to compute values.

Summary

$addFields adds or updates fields with computed values in documents.

It is used inside aggregation pipelines to enrich data without changing the original collection.

You can add multiple computed fields at once using $addFields.