Docs Menu
Docs Home
/
MongoDB Manual
/ / /

$set (aggregation)

On this page

  • Definition
  • Syntax
  • Behavior
  • Examples

Note

Disambiguation

The following page refers to the aggregation stage $set, available starting in MongoDB 4.2 For the update operator $set, see $set.

$set

New in version 4.2.

Adds new fields to documents. $set outputs documents that contain all existing fields from the input documents and newly added fields.

The $set stage is an alias for $addFields.

Both stages are equivalent to a $project stage that explicitly specifies all existing fields in the input documents and adds the new fields.

$set has the following form:

{ $set: { <newField>: <expression>, ... } }

Specify the name of each field to add and set its value to an aggregation expression or an empty object. For more information 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 value of that field with the value of the specified expression.

  • $set appends new fields to existing documents. You can include one or more $set stages in an aggregation operation.

  • $set accepts the embedding of objects where you can set a value to an aggregation expression or to an empty object. For example, the following nested objects are accepted:

    {$set: { a: { b: { } } } }

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

  • To add an element to an existing array field with $set, use with $concatArrays. See example.

Create a sample scores collection with the following:

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

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

db.scores.aggregate( [
{
$set: {
totalHomework: { $sum: "$homework" },
totalQuiz: { $sum: "$quiz" }
}
},
{
$set: {
totalScore: { $add: [ "$totalHomework", "$totalQuiz", "$extraCredit" ] } }
}
] )

The operation returns the following documents:

{
"_id" : 1,
"student" : "Maya",
"homework" : [ 10, 5, 10 ],
"quiz" : [ 10, 8 ],
"extraCredit" : 0,
"totalHomework" : 25,
"totalQuiz" : 18,
"totalScore" : 43
}
{
"_id" : 2,
"student" : "Ryan",
"homework" : [ 5, 6, 5 ],
"quiz" : [ 8, 8 ],
"extraCredit" : 8,
"totalHomework" : 16,
"totalQuiz" : 16,
"totalScore" : 40
}

Use dot notation to add new fields to embedded documents.

Create a sample collection vehicles with the following:

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

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

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

The operation returns the following results:

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

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

Create a sample collection called animals with the following:

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

The following $set operation overrides the cats field:

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

The operation returns the following document:

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

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

Create a sample collection called fruits contains the following documents:

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

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".

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

The operation returns the following:

{ "_id" : "tangerine", "item" : "fruit", "type" : "citrus" }
{ "_id" : "lemon", "item" : "fruit", "type" : "citrus" }
{ "_id" : "grapefruit", "item" : "fruit", "type" : "citrus" }

Create a sample scores collection with the following:

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

You can use $set with a $concatArrays expression to add an element to an existing array field. For example, the following operation uses $set to replace the homework field with a new array whose elements are the current homework array concatenated with another array containing a new score [ 7 ].

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

The operation returns the following:

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

Create a sample scores collection with the following:

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

The following aggregation operation adds a new field quizAverage to each document that contains the average of the quiz array.

db.scores.aggregate( [
{
$set: {
quizAverage: { $avg: "$quiz" }
}
}
] )

The operation returns the following documents:

[
{
_id: 1,
student: 'Maya',
homework: [ 10, 5, 10 ],
quiz: [ 10, 8 ],
extraCredit: 0,
quizAverage: 9
},
{
_id: 2,
student: 'Ryan',
homework: [ 5, 6, 5 ],
quiz: [ 8, 8 ],
extraCredit: 8,
quizAverage: 8
}
]

Back

$searchMeta (aggregation)