liveBook · Manning

$set stage

As explained in MongoDB 8.0 in Action, Third Edition

A $set stage is an aggregation pipeline stage that adds or modifies fields while retaining the other fields in each document.

The $set stage adds fields or modifies existing fields while passing the other document fields through unchanged. It suits pipelines that need focused enrichment rather than a complete document reshaping. section 6.1.2 section 6.1.4

Use $set when you need to:

  • Add a calculated field, such as isDirect, using a conditional expression based on stops. section 6.1.4
  • Modify a field without listing every other field that the document should retain. section 6.1.3
  • Remove a field in the same stage by assigning $$REMOVE, or use $unset when removal is the primary operation. section 6.1.4
  • Prefer it over $project when most input fields should remain and only a few fields need adding or changing. section 6.1.3

Derive a direct-flight indicator

db.routes.aggregate([ { $set: { isDirect: { $eq: ["$stops", 0] }, codeshare: "$$REMOVE" } } ]) This keeps the route document’s other fields, sets isDirect to true when stops equals zero, and removes codeshare. section 6.1.4

db.routes.aggregate([
    {
        $set: {
            isDirect: {
                $eq: ["$stops", 0] // Sets 'isDirect' to true
➥if there are no stops, false otherwise
            },
            codeshare: "$$REMOVE" // Removes 'codeshare'
➥within the same stage
        }
    }
])

Inspect the complete pipeline listing for adding isDirect and removing codeshare within one $set stage. section 6.1.4

Do not confuse the aggregation stage with the update modifier using the same name. In updateOne(), $set changes a stored field and creates it when absent; a filter should identify the intended document precisely. section 4.3.1 section 4.3.1

How MongoDB 8.0 in Action, Third Edition covers it

How deep it goes
Explains purpose, alternatives, conditional expressions, and field removal, but does not descend into execution internals.
Examples
Uses routes documents to derive isDirect from stops and remove codeshare, alongside an updateOne() aircraft change.
What you can do after
Apply it in MongoDB aggregation pipelines to enrich or revise documents without redundantly enumerating retained fields.
How it connects
Connects $set with aggregation pipelines, $unset, $project, $addFields, conditional expressions, and updateOne().

Related concepts

This explainer was generated by Manning's knowledge graph from the text of MongoDB 8.0 in Action, Third Edition. The section links point to the parts of the book it draws on.