Skip to main content

$project

The $project stage in MongoDB's aggregation pipeline is used to selectively pass along specified fields to the next stage of the pipeline. This stage can either add new fields, remove existing fields, or reshape and transform the structure of the documents. It's similar to the SELECT statement in SQL but with more capabilities, such as renaming fields, computing new values, and creating nested structures.

Basic Syntax

The basic syntax of the $project stage is as follows:

db.collection.aggregate([
{
$project: {
field1: <expression>,
field2: <expression>,
// ...
}
}
]);
  • field1, field2, ...: The fields you want to include, exclude, or compute.
  • <expression>: An expression that defines the value of the field. This can be a simple 1 or 0 to include or exclude the field, or a more complex expression to compute the value.

Examples

Including Fields

To include only the amount and status fields:

db.orders.aggregate([
{
$project: { amount: 1, status: 1 }
}
]);

Excluding Fields

To exclude the _id field:

db.orders.aggregate([
{
$project: { _id: 0 }
}
]);

Renaming Fields

To rename the amount field to totalAmount:

db.orders.aggregate([
{
$project: { totalAmount: "$amount" }
}
]);

Computing New Fields

To compute a new field total that is the sum of amount and tax:

db.orders.aggregate([
{
$project: { total: { $add: ["$amount", "$tax"] } }
}
]);

Nested Fields

To create a new nested field details that contains amount and status:

db.orders.aggregate([
{
$project: { details: { amount: "$amount", status: "$status" } }
}
]);

Considerations

  1. Performance: Using $project to reduce the number of fields can improve the performance of subsequent stages by reducing the amount of data that needs to be processed.

  2. Order of Stages: The $project stage can be used at any point in the aggregation pipeline, but its placement can affect performance. For example, placing $project after $match can take advantage of indexes.

  3. Field Names: The $project stage allows you to reshape the document, which includes renaming fields. However, you cannot have two output fields with the same name or use reserved characters in field names.