Skip to main content

馃Ω 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:

[
{ $project: {
name: 1,
bookCount: {$size: "$books"}
}
},
]

馃憪 Who wrote the most books? (We can sort using { $sort: {"bookCount": -1}}.)

Answer
[
{
$project: {
name: 1,
bookCount: {$size: "$books"}
}
},
{ $sort: {"bookCount": -1} },
{ $limit: 1 }
]

馃憪 Find books with exactly three genres (We can $match using { {"bookCount": -1}}.)

Answer
[
{
$match: {
genres: {$size: 3 }
}
},
{$project: {
title: 1,
genres: 1
}}
]