Open In App

MongoDB – countDocuments() Method

Improve
Improve
Like Article
Like
Save
Share
Report

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. 

  • This method does not use metadata to return the count. It performs aggregation of the documents and returns a precise count.
  • You are allowed to use this method in multi-document transactions.
  • This method returns 0 for empty collection or if the given collection is not present in the database.
  • In this method, you are not allowed to use $where, $near, and $nearSphere operators as a part of the query expressions. 

Syntax:

db.Collection_name.countDocuments(

<Selection_criteria>,

{

    limit: <integer>,

    skip: <integer>,

    hint: <string or document>,

    maxTimeMS: <integer>,  

})

Parameters:

  • The first parameter is a selection criteria. The type of this parameter is a document. If you want to count the total number of documents present in the collection pass an empty document({}).
  • The second parameter is optional.

Optional Parameters:

  • limit: It is the maximum number of documents to count.
  • skip: It is the number of documents to skip before counting.
  • hint: It is a document or field that specifies the index to use to support the filter. It can take an index specification document or the index name string and if you specify an index that does not exist, then it will give an error.
  • maxTimeMs: It is the maximum amount of time to allow the query to run.

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

  • Count the number of documents in the given collection:
db.student.countDocuments({})

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

  • Count the number of documents that match the given selection criteria:
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


Last Updated : 05 Feb, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads