Open In App

MongoDB count() Method – db.Collection.count()

The count() method counts the number of documents that match the selection criteria. It returns the number of documents that match the selection criteria. It takes two arguments first one is the selection criteria and the other is optional. 

Syntax:



db.Collection_Name.count(
Selection_criteria,
{
    limit: <integer>,
    skip: <integer>,
    hint: <string or document>,
    maxTimeMS : <integer>,
    readConcern: <string>,
    collation: <document>  
})

Or if we want to count the number of documents in the collection

db.Collection_name.count()

Parameters:

Optional Parameters:



Return Type: 

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

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

db.student.count()

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

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

Note: Here, $gt mean greater than

Article Tags :