liveBook · Manning

$project

As explained in MongoDB 8.0 in Action, Third Edition

$project is a MongoDB aggregation pipeline stage that includes, excludes, or computes fields in the documents it passes through.

$project is an aggregation pipeline stage for reshaping documents by including, excluding, or modifying fields. It is most useful when the result needs a substantially different structure from the input. section 6.1.2 section 6.1.5

Use $project selectively and account for its trade-offs:

  • Include selected fields with a value of 1 and exclude fields with a value of 0; _id is the exception that can be excluded while including other fields. section 6.1.3
  • Prefer $set or $addFields for adding or modifying fields, and $unset for removing fields; these stages make intent clearer and avoid listing every retained field. section 6.1.2 section 6.1.3
  • Place $project near the end when it defines the small, client-facing shape returned after other pipeline work. section 6.1.5

Return only airport route endpoints

db.routes.aggregate([ { $project: { src_airport: 1, dst_airport: 1, _id: 0 } } ]) This produces documents containing only the source and destination airports, while omitting the document identifier and other input fields. section 6.1.5

Listing 6.3 Using the $project operator
db.routes.aggregate([
    {
        $project: {
            src_airport: 1, // Include the source airport
            dst_airport: 1, // Include the destination airport
            _id: 0 // Exclude the MongoDB document ID from the output
        }
    }
])

Inspect the complete aggregation example for selecting route fields and omitting _id. section 6.1.5

How MongoDB 8.0 in Action, Third Edition covers it

How deep it goes
Defines inclusion and exclusion rules, contrasts alternatives, and demonstrates a route projection without covering deeper execution internals.
Examples
Uses a routes aggregation that retains src_airport and dst_airport while removing _id.
What you can do after
Apply $project to construct a reduced aggregation result and choose $set or $unset for narrower field changes.
How it connects
Connects $project with aggregation pipelines, $set, $unset, $addFields, and client-facing document transformation.

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.