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