Open In App

Mongoose | countDocuments() Function

The countDocuments() function is used to count the number of documents that match the filter in a database collection.

Installation of mongoose module: 



npm install mongoose

npm version mongoose

node index.js


Filename: index.js 




const mongoose = require('mongoose');
 
// Database Connection
    useNewUrlParser: true,
    useCreateIndex: true,
    useUnifiedTopology: true
});
 
// User model
const User = mongoose.model('User', {
    name: { type: String },
    age: { type: Number }
});
 
User.countDocuments({age:{$gte:5}}, function (err, count) {
    if (err){
        console.log(err)
    }else{
        console.log("Count :", count)
    }
});

Steps to run the program: 



npm install mongoose

node index.js

So this is how you can use the mongoose countDocuments() function which function counts a number of documents matching filter in a database collection.
 

Article Tags :