Skip to main content

πŸ‘ Adding New Fields to Results

$set / $addFields​

We want to estimate the reading time for a book. But we don't have that field stored in our data. We can use $set for this. If the field exists, it'll get updated, and if it doesn't, it's added.

[
{$project: {
title: 1,
pages: 1,
}
},
{$set: {readingTimeHours: {$divide: [{$multiply: ["$pages", 2]}, 60]}}},
]

πŸ‘ Add a new field, notes, that contains the text PLACEHOLDER for all documents.

Answer
[
{$project:
{
title: 1,
pages: 1,
}
},
{$set: {notes: "PLACEHOLDER"}}
]
info

$set is a new alias for $addFields. You'll still find $addFields on many older posts and documentation.