π 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.
- Atlas UI
- MongoDB Shell
[
{$project: {
title: 1,
pages: 1,
}
},
{$addFields: {readingTimeHours: {$divide: [{$multiply: ["$pages", 2]}, 60]}}},
]
db.books.aggregate([
{$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
- Atlas UI
- MongoDB Shell
[
{$project:
{
title: 1,
pages: 1,
}
},
{$addFields: {notes: "PLACEHOLDER"}}
]
db.books.aggregate([
{$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.