27.9k views
5 votes
How do you reshape fields in the $project stage?

User Panagdu
by
7.3k points

1 Answer

6 votes

Final answer:

The $project stage in MongoDB's aggregation framework is used to reshape documents in a collection. It allows you to include or exclude fields, create new fields, rename fields, and perform various transformations on the data.

Step-by-step explanation:

Reshaping Fields in the $project Stage



In MongoDB's aggregation framework, the $project stage is used to reshape the documents in a collection. It allows you to include or exclude fields, create new fields, rename fields, and perform various transformations on the data.



To reshape fields in the $project stage, you can use the $project operator with an expression. For example, to create a new field 'total' that calculates the sum of two existing fields 'field1' and 'field2', you can use the following syntax:




{
$project: {
total: { $add: ['$field1', '$field2'] }
}
}



In this example, the $add operator adds the values of 'field1' and 'field2' and assigns the result to the new field 'total'. You can also use other operators like $subtract, $multiply, $divide, and functions like $concat, $toLower, $toUpper, etc., to reshape fields in the $project stage based on your requirements.

User Sameer Vartak
by
8.2k points