Count in Aggregation

The $sum accumulator operator adds recursively a specific numeric value to a variable in the process loop. This operator will work only in the $group stage.

To do the SQL version of COUNT() function, we need to construct a $group stage where a field count or your favorite name you want to use, and add 1 to the $sum operator. The following code will produce two elements and one document: _id will have a null value and count containing the total of documents processed.

It can be implemented once your main pipeline is executed.

 
{
	$group : {
		_id : null
		,count: { $sum: 1 }
	}
}
 

Always remove the $limit stage operator if you want to see the real count. This operator give to the pipeline the limit or a specific quantity of documents.

This is a parallel article of Aggregate function and Count.

Related Links

http://docs.mongodb.org/v3.0/reference/operator/aggregation/sum/#grp._S_sum