$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
