Docs Menu
Docs Home
/ /

$set (aggregation stage)

Note

Disambiguation

The following page refers to the aggregation stage $set. For the update operator $set, see $set.

$set

Adds new fields to documents. $set outputs documents that contain all existing fields from the input documents and the new 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.

You can use $set for deployments hosted in the following environments:

  • MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud

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

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

  • You can use $set with 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.

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.

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 $set stage adds two fields: imdbScoreScaled, which multiplies the IMDB rating by 10, and runtimeHours, which divides the runtime by 60 and rounds down to the nearest integer.
Second Stage ($set):
The second $set stage adds totalScore, which sums imdbScoreScaled and runtimeHours computed in the previous stage.

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

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' }
]
...

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' ] }
]
...

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:

[BsonIgnoreExtraElements]
public class Movie
{
[BsonId]
public ObjectId Id { get; set; }
[BsonElement("title")]
public string Title { get; set; } = null!;
[BsonElement("year")]
public int? Year { get; set; }
[BsonElement("runtime")]
public int? Runtime { get; set; }
[BsonElement("rated")]
public string? Rated { get; set; }
[BsonElement("metacritic")]
public int Metacritic { get; set; }
[BsonElement("plot")]
public string? Plot { get; set; }
[BsonElement("type")]
public string? Type { get; set; }
[BsonElement("cast")]
public string[]? Cast { get; set; }
[BsonElement("directors")]
public string[]? Directors { get; set; }
[BsonElement("writers")]
public string[]? Writers { get; set; }
[BsonElement("imdb")]
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;

For related stages, see $addFields.

Back

$searchMeta

On this page