π $count
How can we be sure that this pipeline is returning exactly 15 books?
- Atlas UI
- MongoDB Shell
[
{$match: {$and: [{year: 1985}, {pages: {$gte: 150}}]}},
{$project: {_id: 0, title: 1, year: 1, totalInventory: 1, available: 1}},
{$limit: 15}
]
let moreThan150pages = {pages: {$gte: 150}}
let booksFrom1985WithMoreThan150pages = {$match: {$and: [{year: 1985}, moreThan150pages]}};
let showOnlyTheseFields = {$project: {_id: 0, title: 1, year: 1, totalInventory: 1, available: 1}};
let getJust15books = {$limit: 15};
db.books.aggregate([
booksFrom1985WithMoreThan150pages,
showOnlyTheseFields,
getJust15books,
]);
By counting the books! Let's add a new stage to the pipeline to count those books:
- Atlas UI
- MongoDB Shell
[
{$match: {$and: [{year: 1985}, {pages: {$gte: 150}} ]}},
{$project: {_id: 0, title: 1, year: 1, totalInventory: 1, available: 1}},
{$limit: 15},
{$count: "totalBooks"},
]
let moreThan150pages = {pages: {$gte: 150}}
let booksFrom1985WithMoreThan150pages = {$match: {$and: [{year: 1985}, moreThan150pages]}};
let showOnlyTheseFields = {$project: {_id: 0, title: 1, year: 1, totalInventory: 1, available: 1}};
let getJust15books = {$limit: 15};
let count = {$count: "totalBooks"}
db.books.aggregate([
booksFrom1985WithMoreThan150pages,
showOnlyTheseFields,
getJust15books,
count,
]);
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
- Atlas UI
- MongoDB Shell
[ {$count: "authorCount"} ]
db.authors.aggregate([{$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.
- Atlas UI
- MongoDB Shell
[
{$match: {$and: [{year: 1985}, {pages: {$gte: 150}} ]}},
{$count: "totalBooks"},
{$project: {_id: 0, title: 1, year: 1, totalInventory: 1, available: 1}},
{$limit: 15},
]
let moreThan150pages = {pages: {$gte: 150}}
let booksFrom1985WithMoreThan150pages = {$match: {$and: [{year: 1985}, moreThan150pages]}};
let showOnlyTheseFields = {$project: {_id: 0, title: 1, year: 1, totalInventory: 1, available: 1}};
let getJust15books = {$limit: 15};
let count = {$count: "totalBooks"}
db.books.aggregate([
booksFrom1985WithMoreThan150pages,
count,
showOnlyTheseFields,
getJust15books,
]);