MongoDB Documents Count

By Yashwant Chavan, Views 1186, Last updated on 01-Mar-2019

In this tutorial you will learn how to count number of documents in the collection. mongoDB db.collection.count() method is used to get the count of documents.

tags mongodb

mongoDB Collection Count - db.collection.count()

Returns the count of documents from the collection for the matching query. Refer following count() method syntax.

db.collection.count(query, options)

query - Document type parameter , This is selection criteria of query

options - Optional Document type parameter. This is extra options for modifying the count.

options document contains the following fields

limit - Optional integer type parameter. The maximum number of documents to count.

skip - Optional integer type parameter. Skip number of documents before counting.

hint - Optional string or document type parameter. An index name hint or specification for the query.

maxTimeMS - Optional integer type parameter. The maximum amount of time to allow the query to run.

readConcern - Optional string type parameter. Specifies the read concern.

Existing students collection

> db.students.find()
{ "_id" : 1, "name" : "Yashwant Chavan", "class" : "X" }
{ "_id" : 2, "name" : "Dinesh Patil", "class" : "XI" }
{ "_id" : 3, "name" : "Vishal More", "class" : "X" }
>

Count all documents in a "students" collection, Refer following mongoDB command

db.students.count()

output

> db.students.count()
3
>

Equivalent to above command

db.students.find().count()

output

> db.students.find().count()
3
>

Count all documents with match the query. Count the number of the documents in the students collection with the field class = X

db.students.find({class: "X" }).count() 

output

> db.students.find({class: "X" }).count()
2
>

Equivalent to above command

db.students.find().count({class: "X" })

output

> db.students.count( { class: "X" } )
2
>
Yashwant

Yashwant

Hi there! I am founder of technicalkeeda.com and programming enthusiast. My skills includes Java,J2EE, Spring Framework, Nodejs, PHP and lot more. If you have any idea that you would want me to develop? Lets connect: yashwantchavan[at][gmail.com]