skip to content
Alvin Lucillo

Aggregation count

/ 1 min read

If you’re only going to count the number of documents, there are a lot of ways to do it. But $count aggregation stage is best used as part of an aggregation pipeline. In the example below, $count and countDocuments() returned the same number of documents.

db.accounts.aggregate([{ $count: "total_accounts" }]);
// Result: [ { total_accounts: 52 } ]

db.accounts.countDocuments();
// Result: 52