Open In App

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

Last Updated : 27 Apr, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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 module
const MongoClient = require("mongodb"); 
  
// Connection URL
const url = 'mongodb://localhost:27017/'
  
// 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:


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads