Definition
Note
Disambiguation
$setAdds new fields to documents.
$setoutputs documents that contain all existing fields from the input documents and the new 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.
Important
If the new field name matches an existing field name (including _id), $set overwrites that field's value with the specified expression.
Behavior
$setappends new fields to existing documents. You can include one or more$setstages in an aggregation operation.You can use
$setwith embedded objects. 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 fields to embedded documents (including documents in arrays), use dot notation. See example.
To add an element to an existing array field with
$set, use$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
The following $set operation overwrites the rated field:
db.movies.aggregate( [ { $match: { title: "Baseball" } }, { $set: { rated: "UNRATED" } } ] )
[ { _id: ..., title: 'Baseball', rated: 'UNRATED' } ] ...
You can replace one field with another. The following operation replaces _id with the title field value, then sets title to 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
To add an element to an existing array field, use $concatArrays with $set. The following operation replaces the genres field with a new array that concatenates the current genres array with [ "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 UnionWith() 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
For related stages, see $addFields.