VOOZH about

URL: https://www.geeksforgeeks.org/node-js/mongoose-document-model-count-api/

⇱ Mongoose Document Model.count() API - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Mongoose Document Model.count() API

Last Updated : 1 Aug, 2024

The Model.count() method of the Mongoose API is used to count the number of documents present in the collection based on the given filter condition. It returns the query object and count of documents present in the collection.

Syntax:

Model.count()

Parameters: The Model.count() method accepts two parameters:

  • filter: It is an object to filter the document and based on this condition count() method counts the number of documents in the collection.
  • callback: It is a callback function that will run once execution is completed.

Return Value: The Model.count() function returns a query object and promise.

Setting up Node.js application:

Step 1: Create a Node.js application using the following command:

npm init

Step 2: After creating the NodeJS application, Install the required module using the following command:

npm install mongoose

Project Structure: The project structure will look like this:

👁 Image
 

Database Structure: The database structure will look like this, the following documents are present in the collection.

👁 Image

Example 1: In this example, We have established a database connection using mongoose and defined model over userSchema, having two columns or fields "name" and "age". In the end, we are using count() method on the User model which will count the number of documents present in the collection that matches the filter condition.

  • app.js: Write down the below code in the app.js file:

Step to run the program: To run the application execute the below command from the root directory of the project:

node app.js

Output:

2

Example 2: In this example, we are getting output as a query object that contains meta data information.

  • app.js: Write down the below code in the app.js file:

Step to run the program: To run the application execute the below command from the root directory of the project:

node app.js

Output:

Reference: https://mongoosejs.com/docs/api/model.html#model_Model-count

Comment

Explore