0
0
MongodbHow-ToBeginner · 3 min read

How to Use $set in Aggregation in MongoDB: Syntax and Examples

In MongoDB aggregation, $set is used to add new fields or modify existing fields in documents. It works by specifying field names and their new values inside an aggregation pipeline stage. This allows you to transform documents dynamically during aggregation.
📐

Syntax

The $set stage in an aggregation pipeline takes an object where keys are field names to add or update, and values are expressions or values to assign. It modifies each document passing through the pipeline.

  • Field Name: The name of the field to add or update.
  • Value: The new value or expression for the field.
json
{
  $set: {
    <field1>: <value1>,
    <field2>: <value2>,
    ...
  }
}
💻

Example

This example shows how to add a new field fullName by combining firstName and lastName, and how to update an existing age field by adding 1.

mongodb
db.users.aggregate([
  {
    $set: {
      fullName: { $concat: ["$firstName", " ", "$lastName"] },
      age: { $add: ["$age", 1] }
    }
  }
])
Output
[ { "_id": ObjectId("..."), "firstName": "John", "lastName": "Doe", "age": 31, "fullName": "John Doe" }, { "_id": ObjectId("..."), "firstName": "Jane", "lastName": "Smith", "age": 26, "fullName": "Jane Smith" } ]
⚠️

Common Pitfalls

Common mistakes when using $set include:

  • Using $set outside of an aggregation pipeline stage.
  • Overwriting important fields unintentionally without realizing.
  • Not using expressions correctly, causing errors or unexpected results.

Always verify field names and expressions carefully.

mongodb
/* Wrong: Using $set outside aggregation pipeline */
db.collection.updateMany({}, { $set: { newField: "value" } })

/* Right: Using $set inside aggregation pipeline */
db.collection.aggregate([
  { $set: { newField: "value" } }
])
📊

Quick Reference

UsageDescription
$setAdds or updates fields in documents during aggregation
Field: valueDefines the field name and its new value or expression
ExpressionsUse MongoDB expressions like $concat, $add to compute values
Multiple fieldsYou can set multiple fields in one $set stage
Pipeline stage$set must be inside an aggregation pipeline array

Key Takeaways

Use $set inside aggregation pipelines to add or modify document fields.
$set accepts field-value pairs where values can be expressions or constants.
You can update multiple fields at once with a single $set stage.
Avoid using $set outside aggregation pipelines to prevent errors.
Test expressions carefully to ensure correct field transformations.