How to get the size of a collection using Node.js ?
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.
Syntax:
collection.countDocuments(Query)
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 127.0.0.1

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

index.js
// Requiring moduleconst 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) => { console.log(count_documents); }).catch((err) => { console.log(err.Message); }) }).catch((err) => { // Printing the error message console.log(err.Message); }) |
Run index.js file using below command:
node index.js
Output:



