MongoDB

MongoDB count() and itcount() Example

Hello readers, in today’s world it is useful to count the number of records in a database. In Mongo world, this is pretty straightforward! So in this tutorial, we will see the count() and itcount() methods available in the Mongo database.

1. Introduction

If you have installed the MongoDB application (version 3.6) on Windows or Ubuntu operating system and you wish to learn the count() and itcount() methods then follow the below steps. It is very simple. But before moving further let’s take a look at the Mongo database and its features.

1.1 What is MongoDB?

  • MongoDB is a high-performance NoSQL database where each database has collections which in turn has documents. Each document has a different number of fields, size, content, and is stored in a JSON-like format (i.e. Binary JSON (BSN)
  • The documents in MongoDB doesn’t need to have a schema defined beforehand. Instead, the fields (i.e. records) can be created on the go
  • Data model available within the MongoDB allows developers to represent the hierarchical relationships, store arrays, and other more complex structures easily
  • This NoSQL solution often comes with embedding, auto-sharding, and onboard replication for better scalability and high availability

1.1.1 Why MongoDB?

  • As a NoSQL type database, MongoDB stores the data in the form of a document. Thus, MongoDB offers more flexibility
  • This database supports search by field-name, range queries, and the regular expressions. It often provides queries to return the particular fields inside the documents
  • MongoDB offers indexes to improve the search performance within the NoSQL database
  • To offer horizontal scalability, MongoDB uses sharding by splitting the data across the many MongoDB occurrences
  • Replication: MongoDB can give high availability with the replica sets

1.2 What is a Cursor in MongoDB?

In Mongo world, a cursor is an object that allows developers to iterate through the documents of a Mongo collection. The behavior of cursor allows an automatic iteration across the results of the query; however, developers can explicitly go through the items returned in the cursor object. The below diagram lists 4 documents where the Mongo cursor will point to the first document and then iterate through all the other documents of a collection.

Fig. 1: Pictorial representation of a Cursor in Mongo collection
Fig. 1: Pictorial representation of a Cursor in Mongo collection

1.2.1 Why Cursor in MongoDB?

Cursor offers:

  • A true snapshot of a system i.e. it returns the data in batches and increases the database performance
  • It saves system memory by allowing batch inserts and updates
  • Intelligibility and Clarity on the ad-hoc and complex queries of the sequential nature having large result sets and low consistency requirements
  • Openness to work on small batches of data as developers don’t need to wait for the processing and download of the complete record-set

2. MongoDB count() and itcount() Example

In this tutorial, we will learn how to handle the count() and itcount() methods provided by the Mongo database.

2.1 count() method in the Mongo database

In the Mongo universe, the count() method returns the count of the documents that would match the selection criteria of the find() query. This method does not actually performs the find() operation but instead returns a numerical count of the documents that meet the selection criteria. This method has the following prototype form:

Mongo database ‘count()’ Syntax

> db.collection_name.count(<query>, <options>)

Where:

  • The query is an optional input argument that retrieves the documents from the collection on the basis of a specified selection criteria
  • options is again an optional input argument supplied to the count() method for modifying the numerical value

Do remember:

  • This method is similar to the db.collection_name.find(<query>).count() form
  • This method results in an inaccurate count if any orphaned document exits on a sharded cluster or the chunk migration is in progress

2.2 itcount() method in the Mongo database

The itcount() method is similar to the cursor.count() method and is used to run the query on an existing cursor i.e. this method returns the count of the documents that are remaining in a cursor object. This method has the following prototype form:

Mongo database ‘itcount()’ Syntax

> db.collection_name.find(<query>).itcount()

Where:

  • The query is the selection criteria on which the documents are retrieved from the collection

2.3 Practical usage

Let’s understand the implementation of these methods with the help of the sample snippets.

2.3.1 Start MongoDB

Start a standalone mongod instance as shown below.

Fig. 2: Start Mongo instance
Fig. 2: Start Mongo instance

2.3.2 Connect to the Mongo Instance

Connect with the mongo shell to make a connection with the MongoDB instance on the port 27017 as shown below.

Fig. 3: Connect to Mongo database
Fig. 3: Connect to Mongo database

2.3.3 Create Mongo database and collection

To begin with the implementation, we will need to create a sample database and collection. The below script creates a database called warehouse with a collection of products. Open the Mongo terminal and execute the script.

Database & Collection creation script

> use warehouse

> db.products.insertMany( [
	{ "_id" : "1001", "name" : "AC3 Phone", "brand" : "ACME", "type" : "phone", "price" : 200, "warranty_years" : 1, "available" : "true" },
	{ "_id" : "1002", "name" : "AC7 Phone", "brand" : "ACME", "type" : "phone", "price" : 320, "warranty_years" : 1, "available" : "false" },
	{ "_id" : "1003", "name" : "AC3 Series Charger", "type" : [ "accessory", "charger" ], "price" : 19, "warranty_years" : 0.25, "for" : [ "ac3", "ac7", "ac9" ] },
	{ "_id" : "1004", "name" : "AC3 Case Green", "type" : [ "accessory", "case" ], "color" : "green", "price" : 12, "warranty_years" : 0 },
	{ "_id" : "1005", "name" : "Phone Extended Warranty", "type" : "warranty", "price" : 38, "warranty_years" : 2, "for" : [ "ac3", "ac7", "ac9", "qp7", "qp8", "qp9" ] },
	{ "_id" : "1006", "name" : "AC3 Case Black", "type" : [ "accessory", "case" ], "color" : "black", "price" : 12.5, "warranty_years" : 0.25, "available" : "false", "for" : "ac3" },
	{ "_id" : "1007", "name" : "AC3 Case Red", "type" : [ "accessory", "case" ], "color" : "red", "price" : 12, "warranty_years" : 0.25, "available" : "true", "for" : "ac3" },
	{ "_id" : "1008", "name" : "Phone Service Basic Plan", "type" : "service", "monthly_price" : 40, "limits" : { "voice" : { "units" : "minutes", "n" : 400, "over_rate" : 0.05 }, "data" : { "units" : "gigabytes", "n" : 20, "over_rate" : 1 }, "sms" : { "units" : "texts sent", "n" : 100, "over_rate" : 0.001 } }, "term_years" : 2 },
	{ "_id" : "1009", "name" : "Phone Service Core Plan", "type" : "service", "monthly_price" : 60, "limits" : { "voice" : { "units" : "minutes", "n" : 1000, "over_rate" : 0.05 }, "data" : { "n" : "unlimited", "over_rate" : 0 }, "sms" : { "n" : "unlimited", "over_rate" : 0 } }, "term_years" : 1 },
	{ "_id" : "1010", "name" : "Phone Service Family Plan", "type" : "service", "monthly_price" : 90, "limits" : { "voice" : { "units" : "minutes", "n" : 1200, "over_rate" : 0.05 }, "data" : { "n" : "unlimited", "over_rate" : 0 }, "sms" : { "n" : "unlimited", "over_rate" : 0 } }, "sales_tax" : true, "term_years" : 2 },
	{ "_id" : "1011", "name" : "Cable TV Basic Service Package", "type" : "tv", "monthly_price" : 50, "term_years" : 2, "cancel_penalty" : 25, "sales_tax" : "true", "additional_tariffs" : [ { "kind" : "federal tariff", "amount" : { "percent_of_service" : 0.06 } }, { "kind" : "misc. tariff", "amount" : 2.25 } ] }
] )

The script gives the below output.

Fig. 4: Database & Collection creation
Fig. 4: Database & Collection creation

2.3.4 Check Mongo database and collection

If the script works well, the database and the collection will be shown in the Mongo Workbench. Using the db.collection_name.find() or the db.collection_name.find().pretty() command the documents of a collection will be shown as below.

Fig. 5: Mongo database & collection
Fig. 5: Mongo database & collection

2.3.5 Implementation of ‘count()’ method

Now, go back to the Mongo shell and use the count(<query>) method to display the numerical count of the documents.

Query 1

> db.products.count()

This command will count the total number of the documents in the specified collection (i.e. products).

Fig. 6: Mongo database count() method
Fig. 6: Mongo database count() method

Let’s say developers want to count the number of the documents that match criteria. They can achieve this by simply appending the selection criteria in the find() method. Let’s understand this with the help of an example.

Query 1(a)

> db.products.find( { "available" : "true" } ).count()

This command will only count the number of the documents that match the specified selection criteria.

Fig. 7: Mongo database count() method with selection criteria
Fig. 7: Mongo database count() method with selection criteria

Here if developers have more than one selection criteria, the Query 1(a) can be modified as shown below.

Query 1(b)

> db.products.find( { "available" : "false", "type": "phone" } ).count()

2.3.6 Implementation of ‘itcount()’ method

Refresh the Mongo shell and use the itcount() method to display the count of the documents.

Query 2

> db.products.find( { "available" : "true", "brand": "ACME" } ).itcount()

This command will count the total number of the documents that match the specified selection criteria.

Fig. 8: Mongo database itcount() method
Fig. 8: Mongo database itcount() method

Do remember, to use this method in conjugation with the find() method. If not, the itcount() method generates an exception.

Exception Trace

> db.products.itcount()

2018-03-05T21:11:43.647+0530 E QUERY    [thread1] TypeError: db.products.itcount is not a function :
@(shell):1:1

That’s all for this post. Happy Learning!!

3. Conclusion

In this tutorial, we learned about the count() and itcount() methods of the Mongo database. Developers can download the sample commands in the Downloads section.

4. Download the Eclipse Project

This was an example of the count() and itcount() methods available in the Mongo database.

Download
You can download the full source code of this example here: Codesnippet

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button