Query.prototype.countDocuments()

Parameters
  • [filter] «Object» mongodb selector

  • [callback] «Function» optional params are (error, count)

Returns:
  • «Query» this

Specifies this query as a countDocuments() query. Behaves like count(), except it always does a full collection scan when passed an empty filter {}.

There are also minor differences in how countDocuments() handles $where and a couple geospatial operators. versus count().

Passing a callback executes the query.

This function triggers the following middleware.

  • countDocuments()

Example:

  1. const countQuery = model.where({ 'color': 'black' }).countDocuments();
  2. query.countDocuments({ color: 'black' }).count(callback);
  3. query.countDocuments({ color: 'black' }, callback);
  4. query.where('color', 'black').countDocuments(function(err, count) {
  5. if (err) return handleError(err);
  6. console.log('there are %d kittens', count);
  7. });

The countDocuments() function is similar to count(), but there are a few operators that countDocuments() does not support. Below are the operators that count() supports but countDocuments() does not, and the suggested replacement: