Open In App

MongoDB – countDocuments() Method

In MongoDB, the countDocuments() method counts the number of documents that matches to the selection criteria. It returns a numeric value that represents the total number of documents that match the selection criteria. It takes two arguments first one is the selection criteria and other is optional. 

Syntax:



db.Collection_name.countDocuments(

<Selection_criteria>,



{

    limit: <integer>,

    skip: <integer>,

    hint: <string or document>,

    maxTimeMS: <integer>,  

})

Parameters:

Optional Parameters:

Return:  

This method returns the number of documents that match to selection criteria.

Examples:

In the following examples, we are working with:

Database: gfg

Collections: student

Document: Four documents contains name and age of the students

db.student.countDocuments({})

Here, we are counting the total number of documents present in the student collection.

db.student.countDocuments({age:{$gt:18}})

Here, we are counting the total number of documents in the student collection that matches the given condition, i.e., age is greater than 18.

Note: Here, $gt mean greater than

Article Tags :