Definition
Note
Disambiguation
$setAdds new fields to documents.
$setoutputs documents that contain all existing fields from the input documents and newly added fields.The
$setstage is an alias for$addFields.Both stages are equivalent to a
$projectstage that explicitly specifies all existing fields in the input documents and adds the new fields.
Compatibility
You can use $set for deployments hosted in the following
environments:
MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud
MongoDB Enterprise: The subscription-based, self-managed version of MongoDB
MongoDB Community: The source-available, free-to-use, and self-managed version of MongoDB
Syntax
$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.
Behavior
$setappends new fields to existing documents. You can include one or more$setstages in an aggregation operation.$setaccepts 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.
Examples
The examples on this page use data from the sample_mflix sample dataset. For details on how to load this dataset into your self-managed MongoDB deployment, see Load the sample dataset. If you made any modifications to the sample databases, you may need to drop and recreate the databases to run the examples on this page.
Using Two $set Stages
The following operation uses two $set stages to
include three new fields in the output documents:
db.movies.aggregate( [ { $match: { runtime: { $gt: 1000 } } }, { $set: { imdbScoreScaled: { $multiply: [ "$imdb.rating", 10 ] }, runtimeHours: { $floor: { $divide: [ "$runtime", 60 ] } } } }, { $set: { totalScore: { $add: [ "$imdbScoreScaled", "$runtimeHours" ] } } } ] )
[ { _id: ..., title: 'Baseball', runtime: 1140, imdbScoreScaled: 91, runtimeHours: 19, totalScore: 110 }, { _id: ..., title: 'Centennial', runtime: 1256, imdbScoreScaled: 85, runtimeHours: 20, totalScore: 105 } ] ...
- First Stage (
$set): - The first
$setstage adds two fields:imdbScoreScaled, which multiplies the IMDB rating by10, andruntimeHours, which divides the runtime by60and rounds down to the nearest integer. - Second Stage (
$set): - The second
$setstage addstotalScore, which sumsimdbScoreScaledandruntimeHourscomputed in the previous stage.
Adding Fields to an Embedded Document
Use dot notation to add new fields to embedded documents.
The following aggregation operation adds a new field
normalizedRating to the embedded document imdb:
db.movies.aggregate( [ { $match: { runtime: { $gt: 1000 } } }, { $set: { "imdb.normalizedRating": { $multiply: [ "$imdb.rating", 10 ] } } } ] )
[ { _id: ..., title: 'Baseball', imdb: { '...': '...', normalizedRating: 91 } }, { _id: ..., title: 'Centennial', imdb: { '...': '...', normalizedRating: 85 } } ] ...
Overwriting an Existing Field
Specifying an existing field name in a $set operation
causes the original field to be replaced.
The following $set operation overrides the rated
field:
db.movies.aggregate( [ { $match: { title: "Baseball" } }, { $set: { rated: "UNRATED" } } ] )
[ { _id: ..., title: 'Baseball', rated: 'UNRATED' } ] ...
It is possible to replace one field with another. In the
following example, the title field substitutes for the
_id field.
The following aggregation operation uses $set to replace
the _id field of each document with the value of the
title field and replaces the title field with the
string "movie":
db.movies.aggregate( [ { $match: { runtime: { $gt: 1000 } } }, { $set: { _id: "$title", title: "movie" } } ] )
[ { _id: 'Baseball', title: 'movie' }, { _id: 'Centennial', title: 'movie' } ] ...
Add Element to an Array
You can use $set with a $concatArrays
expression to add an element to an existing array field. The
following operation uses $set to replace the
genres field with a new array whose elements are the
current genres array concatenated with another array
containing a new genre [ "Classic" ]:
db.movies.aggregate( [ { $match: { title: "Baseball" } }, { $set: { genres: { $concatArrays: [ "$genres", [ "Classic" ] ] } } } ] )
[ { _id: ..., title: 'Baseball', genres: [ 'Documentary', 'History', 'Sport', 'Classic' ] } ] ...
Creating a New Field with Existing Fields
The following aggregation operation adds a new field
titleWithYear to each document that concatenates the
movie title with its release year:
db.movies.aggregate( [ { $match: { runtime: { $gt: 1000 } } }, { $set: { titleWithYear: { $concat: [ "$title", " (", { $toString: "$year" }, ")" ] } } } ] )
[ { _id: ..., title: 'Baseball', titleWithYear: 'Baseball (1994)' }, { _id: ..., title: 'Centennial', titleWithYear: 'Centennial (1978)' } ] ...
The C# examples on this page use the sample_mflix database from
the Atlas sample datasets. To learn how to
create a free MongoDB Atlas cluster and load the sample datasets, see
Get Started in the MongoDB
.NET/C# Driver documentation.
The following Movie class models the documents in the
sample_mflix.movies collection:
[] public class Movie { [] public ObjectId Id { get; set; } [] public string Title { get; set; } = null!; [] public int? Year { get; set; } [] public int? Runtime { get; set; } [] public string? Rated { get; set; } [] public int Metacritic { get; set; } [] public string? Plot { get; set; } [] public string? Type { get; set; } [] public string[]? Cast { get; set; } [] public string[]? Directors { get; set; } [] public string[]? Writers { get; set; } [] public ImdbData? Imdb { get; set; } }
To use the MongoDB .NET/C# driver to add a $set stage to an aggregation
pipeline, call the Set() method on a PipelineDefinition object.
The following example creates a pipeline stage that matches on the Movie document with the title
"The Godfather" and sets its Rated field to
"UNRATED":
var pipeline = new EmptyPipelineDefinition<Movie>() .Match(Builders<Movie>.Filter.Eq(m => m.Title, "The Godfather")) .Set(Builders<Movie>.SetFields.Set(m => m.Rated, "UNRATED"));
{ "_id" : "...", "title" : "The Godfather", "runtime" : 175, "rated" : "UNRATED", "metacritic" : 100 }
The Node.js examples on this page use the sample_mflix database from the
Atlas sample datasets. To learn how to create a free
MongoDB Atlas cluster and load the sample datasets, see Get Started in the MongoDB Node.js driver documentation.
To use the MongoDB Node.js driver to add a $set stage to an aggregation
pipeline, use the $set operator in a pipeline object.
The following example creates a pipeline stage that sets the value of the lastupdated field in each movie
document to the value of the Date object. The
example then runs the aggregation pipeline:
const pipeline = [{ $set: { lastupdated: new Date() } }]; const cursor = collection.aggregate(pipeline); return cursor;
Learn More
To learn more about related pipeline stages, see the $addFields
guide.