$project
In MongoDB, the $project operator is a fundamental stage in the Aggregation Framework, and it is used in the MongoDB Shell (mongoshell) to control the shape and content of the output documents during aggregation.
The $project operator allows you to reshape the documents and specify which fields to include or exclude in the output of the aggregation pipeline.
It also enables you to create new computed fields based on expressions using existing fields, constants, or various aggregation operators.
Adds a new field or resets the value of an existing field.
The basic syntax of the $project
operator in the MongoDB Shell is as follows:
{
$project: {
field1: <expression1>,
field2: <expression2>,
...
}
}
Let's go through the main components of the $project
operator:
$project: This is the stage of the aggregation pipeline where you define the projection operation.
field1<true or 1/false or 0>, field2 <true or 1/false or 0>, etc.: These represent the fields you want to include/exclude in the resulting documents. You can specify either the existing fields from the input documents or newly computed fields using aggregation expressions.
<expression1>, <expression2>, etc.: These are aggregation expressions that determine the values of the projected fields. Expressions can include existing field names, literal values, arithmetic operations, conditional expressions, and more.
Using the $project operator, you can:
- Include specific fields in the output documents:
db.collection.aggregate([
{
$project:
{
name: 1,
age: 1
}
}
])
In this example, only the "name" and "age" fields will be included in the output documents, and all other fields will be excluded.
- Exclude specific fields from the output documents:
db.collection.aggregate([
{
$project:
{
_id: 0,
email: 0
}
}
])
In this example, the "_id" and "email" fields will be excluded from the output documents, and all other fields will be included.
- Create computed fields based on expressions:
javascriptdb.collection.aggregate([
{
$project:
{
name: 1,
birthYear:
{ $subtract:
[2023, "$age"] }
}
}
])
In this example, a new field "birthYear" will be added to the output documents, which is calculated by subtracting the "age" field from 2023.
The $project operator is a versatile tool that enables you to shape the output of the aggregation pipeline according to your specific needs. It allows you to control which fields are retained in the output and perform various transformations on the data during the aggregation process.
In this example, I have included the name and age.
0 Comments