$set (aggregation)

Definition

  • $set

New in version 4.2.

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

The $set stage is an alias for $addFields.

Both stages are equivalent to a $project stage thatexplicitly specifies all existing fields in the input documents andadds the new fields.

$set has the following form:

  1. { $set: { <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), $set overwrites the existing valueof that field with the value of the specified expression.

Behavior

$set appends new fields to existing documents. You caninclude one or more $set 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 $set, usewith $concatArrays. See example.

Examples

Using Two $set Stages

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. ])

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

  1. db.scores.aggregate( [
  2. {
  3. $set: {
  4. totalHomework: { $sum: "$homework" },
  5. totalQuiz: { $sum: "$quiz" }
  6. }
  7. },
  8. {
  9. $set: {
  10. totalScore: { $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.

Create a sample collection vehicles with the following:

  1. db.vehicles.insertMany([
  2. { _id: 1, type: "car", specs: { doors: 4, wheels: 4 } },
  3. { _id: 2, type: "motorcycle", specs: { doors: 0, wheels: 2 } },
  4. { _id: 3, type: "jet ski" }
  5. ])

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

  1. db.vehicles.aggregate( [
  2. { $set: { "specs.fuel_type": "unleaded" } }
  3. ] )

The operation returns the following results:

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

Overwriting an existing field

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

Create a sample collection called animals with the following:

  1. db.animals.insertOne( { _id: 1, dogs: 10, cats: 15 } )

The following $set operation overrides the cats field:

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

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.

Create a sample collection called fruits contains the followingdocuments:

  1. db.fruits.insertMany([
  2. { "_id" : 1, "item" : "tangerine", "type" : "citrus" },
  3. { "_id" : 2, "item" : "lemon", "type" : "citrus" },
  4. { "_id" : 3, "item" : "grapefruit", "type" : "citrus" }
  5. ])

The following aggregration operation uses $set to replace the_id field of each document with the value of the item field,and replaces the item field with a string "fruit".

  1. db.fruits.aggregate( [
  2. { $set: { _id : "$item", item: "fruit" } }
  3. ] )

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 $set with a $concatArraysexpression to add an element to an existing array field. For example,the following operation uses $set 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. { $set: { 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 }