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

Mongoose Schemas

To be able to execute CRUD operations to interact with our database, we have to model our data. By this, we’ll create schemas that will be used to send data. In our example, we’ll create a document posting document details coming from Client and go to Server where the POST method will receive data and will grave it into the database, through our schema.

Read moreMongoose Schemas