Skip to main content

πŸ‘ $count

How can we be sure that this pipeline is returning exactly 15 books?

[
{$match: {$and: [{year: 1985}, {pages: {$gte: 150}}]}},
{$project: {_id: 0, title: 1, year: 1, totalInventory: 1, available: 1}},
{$limit: 15}
]

By counting the books! Let's add a new stage to the pipeline to count those books:

[
{$match: {$and: [{year: 1985}, {pages: {$gte: 150}} ]}},
{$project: {_id: 0, title: 1, year: 1, totalInventory: 1, available: 1}},
{$limit: 15},
{$count: "totalBooks"},
]

Here, $count will count the resulting docs and will return a document with just one field: totalBooks.

{
totalBooks: 15
}

πŸ‘ How many authors do we have in our authors collection?

Answer
[ {$count: "authorCount"} ]

The order of stages is important​

If we count after the $match stage, the document we're passing to the next steps contains only the totalBooks field. So the $project stage will return an empty document.

[
{$match: {$and: [{year: 1985}, {pages: {$gte: 150}} ]}},
{$count: "totalBooks"},
{$project: {_id: 0, title: 1, year: 1, totalInventory: 1, available: 1}},
{$limit: 15},
]