Counting the number of documents using count or aggregation framework in MongoDB

To count the number of documents inside a collection we have two choices: Count method or using The $sum and $group or $count in the aggregation framework

Count method in MongoDB

The count method is used to count the number of documents. The count method takes one parameter which is a query (See more about query operators: [Query operators]).

Counting the number of elements inside a MongoDB collection using Count

db.articles.count({});

RDBMS equivalent of count

SELECT count(*) FROM articles;

Counting the number of elements inside a MongoDB collection using a query parameter

db.articles.count({name: {$ne: "article 1"}});

RDBMS equivalent count using where condition

SELECT count(*) FROM articles where name!='article 1';

Counting the number of elements using Aggregate ($sum, $group, $count)

Counting the number of elements inside a MongoDB collection using $count

The $count stage is equivalent to the following $group + $project sequence.

db.articles.aggregate([
	{
		$match: {name: {$ne: "article 1"}}
	},
	{
		$count: "myCount"
	}
]);

Counting the number of elements inside a MongoDB collection using $group and $sum

When using group by with a null _id, it selects all the elements inside the selected collection, all what left to do is calculacting the number of documents using $sum of 1 on every documents and project only the field myCount.

db.articles.aggregate([
	{
		$match: {name: {$ne: "article 1"}}
	},
	{ 	$group: { _id: null, myCount: { $sum: 1 } } },
   	{ 	$project: { _id: 0 } }
]);