🦸 Size of an array
What if we want to know how many aliases an author has? To do that, we can use $size
, adding the array field that we're interested in:
- Atlas UI
- MongoDB Shell
[
{ $project: {
name: 1,
bookCount: {$size: "$books"}
}
},
]
db.authors.aggregate([
{ $project: {
name: 1,
bookCount: {$size: "$books"}
}
},
])
👐 Who wrote the most books? (We can sort using { $sort: {"bookCount": -1}}
.)
Answer
- Atlas UI
- MongoDB Shell
[
{
$project: {
name: 1,
bookCount: {$size: "$books"}
}
},
{ $sort: {"bookCount": -1} },
{ $limit: 1 }
]
let addNumberBooks = {
$project: {
name: 1,
bookCount: {$size: "$books"}
}
}
let orderByNumberOfBooksDesc = { $sort: {"bookCount": -1} }
let getOne = { $limit: 1 }
db.authors.aggregate([
addNumberBooks,
orderByNumberOfBooksDesc,
getOne,
])
👐 Find books with exactly three genres (We can $match using { {"bookCount": -1}}
.)
Answer
- Atlas UI
- MongoDB Shell
[
{
$match: {
genres: {$size: 3 }
}
},
{$project: {
title: 1,
genres: 1
}}
]
db.books.aggregate([
{
$match: {
genres: {$size: 3 }
}
},
{$project: {
title: 1,
genres: 1
}}
])