Open In App

Mongoose Document Model.count() API

Last Updated : 19 Sep, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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:

 

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

 

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:

Javascript




// Require mongoose module
const mongoose = require("mongoose");
  
// Set Up the Database connection
    useNewUrlParser: true,
    useUnifiedTopology: true,
});
  
const userSchema = new mongoose.Schema({
    name: String,
    age: Number
});
  
// Defining userSchema model
const User = mongoose.model("User", userSchema);
User.count({ age: 20 }).then(count => {
    console.log(count)
})


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:

Javascript




// Require mongoose module
const mongoose = require("mongoose");
  
// Set Up the Database connection
    useNewUrlParser: true,
    useUnifiedTopology: true,
});
  
const userSchema = new mongoose.Schema({
    name: String,
    age: Number
});
  
// Defining userSchema model
const User = mongoose.model("User", userSchema);
const output = User.count({ age: 20 })
console.log(output)


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



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads