liveBook · Manning

$unset stage

As explained in MongoDB 8.0 in Action, Third Edition

The $unset stage is an aggregation pipeline stage that removes specified fields from each document.

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

How MongoDB 8.0 in Action, Third Edition covers it

How deep it goes
Defines behavior, contrasts $project, and demonstrates field-list syntax, but does not detail execution internals.
Examples
Uses route documents to remove codeshare and stops, then combines $set with $$REMOVE to remove codeshare conditionally.
What it assumes
Assumes familiarity with aggregation pipelines and document fields, while contrasting selective removal with explicit projection.
What you can do after
Apply it via MongoDB aggregation pipelines to remove selected output fields without listing every retained field.
How it connects
Connects $unset with aggregation pipelines, $set, $project, $match, and $$REMOVE.

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.