The $project stage lets you choose which fields to keep, remove, or create in your MongoDB query results. It helps you shape the output to show only what you want.
0
0
$project stage for shaping output in MongoDB
Introduction
You want to show only a few fields from each document, hiding the rest.
You want to rename fields or create new fields based on existing data.
You want to calculate new values for each document before showing results.
You want to simplify the output to make it easier to read or use in your app.
Syntax
MongoDB
db.collection.aggregate([
{ $project: {
field1: 1,
field2: 1,
newField: { $someOperator: "$existingField" },
_id: 0
}}
])Use 1 to include a field and 0 to exclude it.
You can create new fields using expressions inside $project.
Examples
This shows only the
name and age fields, hiding the _id field.MongoDB
db.users.aggregate([
{ $project: { name: 1, age: 1, _id: 0 } }
])This creates a new field
totalPrice by multiplying price and quantity.MongoDB
db.orders.aggregate([
{ $project: { totalPrice: { $multiply: ["$price", "$quantity"] }, _id: 0 } }
])This renames the
name field to productName and includes price.MongoDB
db.products.aggregate([
{ $project: { productName: "$name", price: 1, _id: 0 } }
])Sample Program
This query creates a new field fullName by joining firstName and lastName, includes department, and hides _id.
MongoDB
db.employees.aggregate([
{ $project: {
fullName: { $concat: ["$firstName", " ", "$lastName"] },
department: 1,
_id: 0
}}
])OutputSuccess
Important Notes
If you include any field with 1, MongoDB excludes all others by default except _id.
To hide _id, you must explicitly set _id: 0.
You can use many MongoDB expressions inside $project to transform data.
Summary
$project shapes the output by selecting, renaming, or creating fields.
Use 1 to keep fields, 0 to hide them.
You can build new fields using expressions like $concat or $multiply.