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.
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
const MongoClient = require( "mongodb" );
const databasename = "GFG" ;
MongoClient.connect(url).then((client) => {
const connect = client.db(databasename);
const collection = connect.collection( "aayush" );
collection.countDocuments().then((count_documents) => {
console.log(count_documents);
}). catch ((err) => {
console.log(err.Message);
})
}). catch ((err) => {
console.log(err.Message);
})
|
Run index.js file using below command:
node index.js
Output:
Share your thoughts in the comments
Please Login to comment...