MongoDB Aggregation $addFields

 

Aggregation $addFields

This aggregation stage adds new fields to documents.

Example

In this example, we are using the "sample_restaurants" database loaded from our sample data in the section.

db.restaurants.aggregate([
  {
    $addFields: {
      avgGrade: { $avg: "$grades.score" }
    }
  },
  {
    $project: {
      "name": 1,
      "avgGrade": 1
    }
  },
  {
    $limit: 5
  }
])

This will return the documents along with a new field, avgGrade, which will contain the average of each restaurants grades.score.


 
$addFields

Login
ADS CODE