Open In App

Mongoose count() Function

Last Updated : 10 Jun, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

When building applications using MongoDB with Mongoose, one common requirement is to count the number of documents in a collection. Whether you want to know how many users exist, how many orders have been placed, or simply verify how many documents match certain criteria.

Mongoose’s count() function provides a simple and efficient way to get that information. In this article, we will explain about the Mongoose count() function provides a simple and efficient way to get that information.

What is the count() Function in Mongoose?

The count() function in Mongoose is a method that modifies a query to return the number of documents matching the query criteria instead of returning the documents themselves. The Query.prototype.count() function is used to count the number of documents in a collection. This function basically specifies this query as a count query.

  • We call it on a query object, usually after .find().
  • It returns a count (number) of matching documents.
  • It accepts an optional callback function to process the count result.
  • If no callback is provided, it returns a Query object that supports Promises, enabling modern async usage.

Syntax: 

Query.prototype.count()

Parameters:

  • callback (Optional): A function (err, count) called with the result or error
  • When no callback is provided, .count() returns a Query object, allowing chaining or usage with Promises.
  • The callback receives two arguments: an error object (if any), and the count number.

Why use count()?

  • To determine how many documents match certain criteria without fetching all data.
  • Useful for pagination (knowing total records).
  • Helps in reporting and analytics by quickly counting records.
  • Saves bandwidth and processing time compared to fetching entire documents.

Installation of mongoose module

Step 1: You can visit the link to Install mongoose module. You can install this package by using this command. 

npm install mongoose

Step 2: After installing the mongoose module, you can check your mongoose version in command prompt using the command. 

npm version mongoose

After that, you can just create a folder and add a file for example, index.js as shown below.

Database:
 

Step 3: Create Project Structure

Your project should have a simple structure like:

Example 1: Counting All Documents in a Collection

In this example, we will count all user documents in the collection 

const mongoose = require('mongoose');

// Database connection
mongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks', {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true
});

// User model
const User = mongoose.model('User', {
name: { type: String },
age: { type: Number }
});

var query = User.find();
query.count(function (err, count) {
if (err) console.log(err)
else console.log("Count is", count)
});

Steps to run the program: 

Run index.js file using below command: 

node index.js

Output: 

Count is 4

Explanation:

  • We connect to the MongoDB database named geeksforgeeks.
  • Define a User schema with two fields: name and age.
  • Use User.find() without filters to select all documents.
  • Call .count() on the query to count how many users exist.
  • The callback logs the count or an error.

Example 2: Counting Documents with a Filter in an Express Server

This example demonstrates how you can integrate counting documents inside an API server.

const express = require('express');
const mongoose = require('mongoose');
const app = express();

mongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks', {
useNewUrlParser: true,
useUnifiedTopology: true
});

const User = mongoose.model('User', {
name: String,
age: Number
});

// API endpoint to count users older than 20
app.get('/count-users-over-20', (req, res) => {
User.find({ age: { $gt: 20 } }).count(function(err, count) {
if (err) {
res.status(500).send("Error counting users");
} else {
res.json({ count: count });
}
});
});

app.listen(3000, () => {
console.log("Server running on http://localhost:3000");
});

Steps to run the program:  The project structure will look like this: 

Run index.js file using below command: 

node index.js

Output: 

Server running on http://localhost:3000
Count: 2

Why Counting Documents is Crucial in Real Applications

  • Pagination: You can calculate total pages based on document count.
  • Dashboards & Reports: Quick counts give insights without loading full data.
  • Data Validation: Check if certain records exist by counting matching docs.
  • Performance: Counting is lighter than fetching full data sets.

Best Practices for Using count() in Mongoose

  • Use .countDocuments() for accuracy: MongoDB recommends this over .count() for filtered queries.
  • Handle errors carefully: Always check errors in your callbacks or promise rejections.
  • Use async/await for cleaner code: You can convert count queries into promises by calling .exec().
  • Avoid counting large datasets frequently: Cache counts if data does not change often for better performance.
  • Leverage GUI tools: Use MongoDB Compass or Robo3T to visually inspect collection counts.

Conclusion

Counting documents is a fundamental operation when working with MongoDB and Mongoose. The .count() function makes it easy to perform this operation directly on your queries. By mastering counting techniques and best practices, you can build scalable and efficient applications that handle data intelligently. For modern and production-grade applications, consider switching to .countDocuments() for better reliability and always handle asynchronous errors properly.


Next Article

Similar Reads