Skip to main content

πŸ‘ Adding New Fields to Results

$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 $addFields for this. If the field exists, it'll get updated, and if it doesn't, it's added.

[
{$project: {
title: 1,
pages: 1,
}
},
{$addFields: {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,
}
},
{$addFields: {notes: "PLACEHOLDER"}}
]
info

$set is an alias for $addFields that you'll find on many older posts and documentation.