Tutorials References Exercises Videos Menu
Create Website Get Certified Upgrade

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 Intro to Aggregations section.

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

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