MongoDB Aggregation Framework - $project stage

💚 $project stage:

In the MongoDB aggregation framework, the $project stage is used to transform or reshape the documents in the collection during the aggregation pipeline. It allows us to include or exclude documents, create a new field or rename a field, and more.

✌ Syntax:
{ $project: { field1: 1, // Include field1 field2: 0, // Exclude field2 field3: "$age" //expression or operation that perform more complex transformation or operation // You can add more fields and transformations here } }

💧 Renaming a field:
{ $project: { newFieldName: "$oldFieldName" } }

💧 Created a new calculated field:
{ $project: { newField: { $add: ["$field1", "$field2"] } } }

Explanation:
{
  "_id": 1,
  "totalAmount": 100,
  "discount": 10
},
{
  "_id": 2,
  "totalAmount": 200,
  "discount": 20
}

db.orders.aggregate([ { $project: { _id: 1, totalAmount: 1, discount: 1, finalAmount: { $subtract: ["$totalAmount", "$discount"] } } } ]);

Output:
{ "_id": 1, "totalAmount": 100, "discount": 10, "finalAmount": 90 }, { "_id": 2, "totalAmount": 200, "discount": 20, "finalAmount": 180 }


💧 Created a new field:
db.persons.aggregate([ {$project: {
            _id: 0,
            name: 1,
            personInfo: {
                gen: "$gender",
                color: "$eyeColor",
                address: "$company.location.country"
        }}}, ])




Post a Comment

Previous Post Next Post