What is estimatedDocumentCount() in Mongoose?

Overview

The estimatedDocumentCount() or Model.estimatedDocumentCount() of Mongoose gets the number of documents in a collection. It is fast because it uses the collection metadata rather than scanning the entire collection. It is different from the deprecated count() method and the countDocument() because it uses indexes and doesn’t do a full collection scan.

Therefore, the estimatedDocumentCount() is a way to quickly get the number of documents a collection has.

Syntax

// Without Parameter
await Model.estimatedDocumentCount();
// With a callback as parameter
Model.estimatedDocumentCount(function(error, count){})

Paremeters

  • Callback function: The estimatedDocumentCount() can take a callback function as a parameter. The callback function is called after the estimatedDocumentCount() is executed to check for error or use the returned count value.

  • Options: It could also optionally take an object option as a parameter. The options affect the count behavior. An example is maxTimeMS, which is an integer, and it is the maximum amount of time to allow the count to run.

Example

Let’s demonstrate the power of this method.

We can set up our Expressjs server, create a Person schema and connect to our database. See the code below:

require('dotenv').config();
const express = require('express');
const app = express();
const mongoose = require("mongoose");
// CONNECT TO OUR DATABASE
mongoose.connect(process.env.DB_ONLINE, {
useNewUrlParser: true,
});
const db = mongoose.connection;
db.on("error", () => {
console.error.bind(console, 'MongoDB connection error:')
})
db.on("open", () => {
console.log("database running successfully");
})
// PERSON SCHEMA
const Person = mongoose.model("Person", new mongoose.Schema({
name: String,
title: String,
commit: Number
})
)
// select our port
const port = process.env.PORT || 3000;
app.listen(port, function() {
console.log(`Listening on port ${port}`);
});

Now let’s create our routes. We will create two routes. One will be "/" and the other will be "/document-count". Before that, let’s make a function that will automatically create some documents for us.

// function that will create many documents at once
const createManyDocuments = async () =>{
try {
//This deletes all documents present in the collection
await Person.deleteMany({});
// This creates many documents at once
let persons = await Person.create(
[
{
name: "Theodore",
title: "MERN Stack Developer",
commit: 1000
},
{
name: "Chidera",
title: "Network Administrator",
commit: 1000
},
{
name: "Elijah",
title: "Backend Developer",
commit: 200
},
{
name: "Emeka",
title: "Web Developer",
commit: 500
}
]
)
// return all documents created
return persons
}
catch (error) {
// if error occurs, then throw
throw error
}
}

This method will be called inside the route "/" as shown below:

// default route that creates and sends back created documents
app.get("/", async (req, res) => {
// createmanyDocuments create person documents and returns them
let persons = await createManyDocuments();
// a json response of the documents created is sent to the user
res.json({documents: persons});
});

Once the default route "/"is accessed, the following response is returned:

As seen above, once the documents are created, a json response is returned to show the documents created.

Now let’s take a look at the wonderful estimatedDocumentCount() in the second route "/document-count".

// the route that gets total count of all documents in our person collection
app.get("/document-count", async (req, res)=>{
try{
// Person.estimatedDocumentCount() returns total number of documents
let count = await Person.estimatedDocumentCount();
// a json response of the total count is sent to the user
res.json({documentCount: count})
}catch(error){
// if error occurs, then throw
throw error
}
})

The estimatedDocumentCount() was called on the Person collection from the code above. And as we know, only four documents were created. So when the route "/" is accessed, the number 4 will be returned, as seen below.

Free Resources