The $unset stage removes specified fields from each document during aggregation while allowing other fields to pass through unchanged. It is useful when an output should retain most input fields but omit a few unnecessary ones. section 6.1.2 section 6.1.4
Prefer $unset when:
- You need to remove only a small number of fields from otherwise useful documents. section 6.1.4
- You want clearer and shorter pipelines than explicit field inclusion with $project. section 6.1.3
- You need to remove several fields with one stage, such as codeshare and stops. section 6.1.4
Remove fields from route documents
db.routes.aggregate([ { $unset: ["codeshare", "stops"] } ]) This keeps the remaining route and airline information while excluding the two named fields. When removal accompanies a calculated field, $set can add isDirect and assign codeshare: "$$REMOVE" in the same stage. section 6.1.4
Listing 6.2 Using the $set and $unset operators
db.routes.aggregate([
{
$unset: ["codeshare", "stops"] // Excludes 'codeshare'
➥and 'stops' fields from the output documents
}
])
Open the complete route-collection listing for copyable $unset syntax. section 6.1.4
