馃Ω Missing Data
Sometimes, we're missing a field we're looking for (it's not there, as documents in a collection can be polymorphic, so this field is null
). For these cases, we can check if something is there using $ifNull
and add a default value.
- Atlas UI
- MongoDB Shell
[
{
$project: {
name: 1,
books: { $ifNull: ["$books", []]},
}
}
]
let getAuthorsWithBooks = {
$project: {
name: 1,
books: { $ifNull: ["$books", []]},
}
}
db.authors.aggregate([
getAuthorsWithBooks,
])