w3resource logo


Mongodb count cursor method

MongoDB count function - cursor method

rating has average rating 8 out of 10. Total 10 users rated.

<<PreviousNext>>

Description

In this page we are going to discuss the usage of count function in mongodb. The count() function returns the number of documents in a specified collection.

Our database name is 'myinfo' and our collection name is 'testtable'. Here, is the collection bellow.

Sample collection "testtable"

mongodb sample testtable

MongoDB count() example

If we want to get the number of documents in the collection "testtable", the following mongodb command can be used :

> db.testtable.count()

Output of the command

MongoDB count example1

MongoDB count() example with condition

If we want to get the number of documents in the collection "testtable" where the sex is 'Male' , the following mongodb command can be used :

> db.testtable.find({"sex":"Male"}).count()

Output of the command

MongoDB count example2

MongoDB count() example with conditional operator

If we want to get the number of documents in the collection "testtable" where the sex is 'Male' and education is 'M.C.A.' , the following mongodb command can be used :

> db.testtable.find({"sex":"Male","education":"M.C.A."}).count()

Output of the command

MongoDB count example3

MongoDB count() example with skip()

The count() by default ignores the skip() and limit() parameters.

If we want to get the number of documents after skipping the first document from the collection "testtable" where the sex is 'Male', the following mongodb command can be attempted :

> db.testtable.find({"sex":"Male"}).skip(1).count()

Output of the command

MongoDB count example4

The above statement ignores the skip() parameter.

MongoDB count() example with true parameter

The 'true' parameter with count() can be used to consider the skip and limit values in the calculation.

If we want to get the number of documents after skipping the first document and consider it in the calculation, from the collection "testtable" where the sex is 'Male', the following mongodb command can be used:

> db.testtable.find({"sex":"Male"}).skip(1).count(true)

Output of the command

MongoDB count example5

MongoDB count() example with dot notation

If we want to get the number of documents in the collection "testtable" where the 'community_name' under the 'extra' is 'MODERN MUSIC', the following mongodb command can be used :

> db.testtable.find({"extra.community_name" : "MODERN MUSIC"}).count()

Output of the command

MongoDB count example1

photo credit: indrarado via photopin cc

<<PreviousNext>>

Rate this tutorial


Your Rating: not set

Share this tutorial

RSS Feed