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.
// Without Parameterawait Model.estimatedDocumentCount();// With a callback as parameterModel.estimatedDocumentCount(function(error, count){})
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.
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 DATABASEmongoose.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 SCHEMAconst Person = mongoose.model("Person", new mongoose.Schema({name: String,title: String,commit: Number}))// select our portconst 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 onceconst createManyDocuments = async () =>{try {//This deletes all documents present in the collectionawait Person.deleteMany({});// This creates many documents at oncelet 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 createdreturn persons}catch (error) {// if error occurs, then throwthrow error}}
This method will be called inside the route "/"
as shown below:
// default route that creates and sends back created documentsapp.get("/", async (req, res) => {// createmanyDocuments create person documents and returns themlet persons = await createManyDocuments();// a json response of the documents created is sent to the userres.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 collectionapp.get("/document-count", async (req, res)=>{try{// Person.estimatedDocumentCount() returns total number of documentslet count = await Person.estimatedDocumentCount();// a json response of the total count is sent to the userres.json({documentCount: count})}catch(error){// if error occurs, then throwthrow 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.