Skip to content
Related Articles

Related Articles

Improve Article

How to get the size of a collection using Node.js ?

  • Last Updated : 27 Apr, 2021

The collection.countDocuments() is the method of the mongodb module in the node.js that is used to count the total number of documents present in the collection of the particular database in the MongoDB.



Parameters: This method takes the following one parameter which is not required by default:

  • Query: It is the query to count the filter documents from the collections.

Return type: This method returns the promises.

Installing module: Install the mongodb module using the following command:

npm install mongodb

Project structure: It will look like this.

Running Server on Local IP: Data is the directory where the MongoDB server is present.

mongod --dbpath=data --bind_ip

MongoDB Database: Following is some sample data in our database.



// Requiring module
const MongoClient = require("mongodb"); 
// Connection URL
// Database name 
const databasename = "GFG";
MongoClient.connect(url).then((client) => { 
    const connect = client.db(databasename); 
    // Connect to collection 
    const collection = connect.collection("aayush"); 
    // Count the total documents
     collection.countDocuments().then((count_documents) => {
     }).catch((err) => {
}).catch((err) => { 
    // Printing the error message 

Run index.js file using below command:

node index.js


My Personal Notes arrow_drop_up
Recommended Articles
Page :