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
