$addFields (aggregation)

Definition

  • $addFields

New in version 3.4.

Adds new fields to documents. $addFields outputs documents thatcontain all existing fields from the input documents and newlyadded fields.

The $addFields stage is equivalent to a$project stage that explicitly specifies all existingfields in the input documents and adds the new fields.

Note

Starting in version 4.2, MongoDB adds a new aggregation pipelinestage $set that is an alias for $addFields.

$addFields has the following form:

  1. { $addFields: { <newField>: <expression>, ... } }

Specify the name of each field to add and set its value to anaggregation expression. For moreinformation on expressions, see Expressions.

Important

If the name of the new field is the same as an existing field name(including _id), $addFields overwrites the existing valueof that field with the value of the specified expression.

Behavior

$addFields appends new fields to existing documents. You caninclude one or more $addFields stages in an aggregation operation.

To add field or fields to embedded documents (including documents inarrays) use the dot notation. See example.

To add an element to an existing array field with $addFields, usewith $concatArrays. See example.

Examples

Using Two $addFields Stages

A collection called scores contains the following documents:

  1. {
  2. _id: 1,
  3. student: "Maya",
  4. homework: [ 10, 5, 10 ],
  5. quiz: [ 10, 8 ],
  6. extraCredit: 0
  7. }
  8. {
  9. _id: 2,
  10. student: "Ryan",
  11. homework: [ 5, 6, 5 ],
  12. quiz: [ 8, 8 ],
  13. extraCredit: 8
  14. }

The following operation uses two $addFields stages toinclude three new fields in the output documents:

  1. db.scores.aggregate( [
  2. {
  3. $addFields: {
  4. totalHomework: { $sum: "$homework" } ,
  5. totalQuiz: { $sum: "$quiz" }
  6. }
  7. },
  8. {
  9. $addFields: { totalScore:
  10. { $add: [ "$totalHomework", "$totalQuiz", "$extraCredit" ] } }
  11. }
  12. ] )

The operation returns the following documents:

  1. {
  2. "_id" : 1,
  3. "student" : "Maya",
  4. "homework" : [ 10, 5, 10 ],
  5. "quiz" : [ 10, 8 ],
  6. "extraCredit" : 0,
  7. "totalHomework" : 25,
  8. "totalQuiz" : 18,
  9. "totalScore" : 43
  10. }
  11. {
  12. "_id" : 2,
  13. "student" : "Ryan",
  14. "homework" : [ 5, 6, 5 ],
  15. "quiz" : [ 8, 8 ],
  16. "extraCredit" : 8,
  17. "totalHomework" : 16,
  18. "totalQuiz" : 16,
  19. "totalScore" : 40
  20. }

Adding Fields to an Embedded Document

Use dot notation to add new fields to embedded documents.A collection called vehicles contains the following documents:

  1. { _id: 1, type: "car", specs: { doors: 4, wheels: 4 } }
  2. { _id: 2, type: "motorcycle", specs: { doors: 0, wheels: 2 } }
  3. { _id: 3, type: "jet ski" }

The following aggregation operation adds a new field fuel_type tothe embedded document specs.

  1. db.vehicles.aggregate( [
  2. {
  3. $addFields: {
  4. "specs.fuel_type": "unleaded"
  5. }
  6. }
  7. ] )

The operation returns the following results:

  1. { _id: 1, type: "car",
  2. specs: { doors: 4, wheels: 4, fuel_type: "unleaded" } }
  3. { _id: 2, type: "motorcycle",
  4. specs: { doors: 0, wheels: 2, fuel_type: "unleaded" } }
  5. { _id: 3, type: "jet ski",
  6. specs: { fuel_type: "unleaded" } }

Overwriting an existing field

Specifying an existing field name in an $addFields operationcauses the original field to be replaced.

A collection called animals contains the following document:

  1. { _id: 1, dogs: 10, cats: 15 }

The following $addFields operation specifies the cats field.

  1. db.animals.aggregate( [
  2. {
  3. $addFields: { "cats": 20 }
  4. }
  5. ] )

The operation returns the following document:

  1. { _id: 1, dogs: 10, cats: 20 }

It is possible to replace one field with another. In the followingexample the item field substitutes for the _id field.

A collection called fruit contains the following documents:

  1. { "_id" : 1, "item" : "tangerine", "type" : "citrus" }
  2. { "_id" : 2, "item" : "lemon", "type" : "citrus" }
  3. { "_id" : 3, "item" : "grapefruit", "type" : "citrus" }

The following aggregration operation uses $addFields to replacethe _id field of each document with the value of the itemfield, and replaces the item field with a static value.

  1. db.fruit.aggregate( [
  2. {
  3. $addFields: {
  4. _id : "$item",
  5. item: "fruit"
  6. }
  7. }
  8. ] )

The operation returns the following:

  1. { "_id" : "tangerine", "item" : "fruit", "type" : "citrus" }
  2. { "_id" : "lemon", "item" : "fruit", "type" : "citrus" }
  3. { "_id" : "grapefruit", "item" : "fruit", "type" : "citrus" }

Add Element to an Array

Create a sample scores collection with the following:

  1. db.scores.insertMany([
  2. { _id: 1, student: "Maya", homework: [ 10, 5, 10 ], quiz: [ 10, 8 ], extraCredit: 0 },
  3. { _id: 2, student: "Ryan", homework: [ 5, 6, 5 ], quiz: [ 8, 8 ], extraCredit: 8 }
  4. ])

You can use $addFields with a $concatArraysexpression to add an element to an existing array field. For example,the following operation uses $addFields to replace thehomework field with a new array whose elements are the currenthomework array concatenated with another array containing a newscore [ 7 ].

  1. db.scores.aggregate([
  2. { $match: { _id: 1 } },
  3. { $addFields: { homework: { $concatArrays: [ "$homework", [ 7 ] ] } } }
  4. ])

The operation returns the following:

  1. { "_id" : 1, "student" : "Maya", "homework" : [ 10, 5, 10, 7 ], "quiz" : [ 10, 8 ], "extraCredit" : 0 }