MongoDB itcount() and count()

Introduction

When you’re storing data in MongoDB, there may be times that you need to know how many documents are in a given collection. Fortunately, MongoDB provides two helpful methods that allow you to get the information you need. In this article, we’ll take a look at the MongoDB itcount() and count() methods and discuss how they can be used to interact with a MongoDB database.

Prerequisite

Before proceeding with this tutorial, make sure that MongoDB server is installed and configured on your system.

What is MongoDB?

If you’re just getting started with MongoDB, there are a few key things to know about the product. MongoDB is a NoSQL database that’s made up of collections; each collection consists of one or more documents. A MongoDB document has a JSON format and can contain a variety of content. MongoDB doesn’t require a schema, which makes it an ideal candidate for unstructured or less-structured data– fields for a given document are created on the fly.

Advantages of using MongoDB

There are multiple benefits to using MongoDB to store and manage your data:

  • MongoDB allows users to take advantage of indexing which enhances query efficiency.
  • MongoDB replication offers high availability.
  • MongoDB is flexible– it stores information in the form of a document without requiring a pre-defined schema.

Creating the Sample Dataset

In this section, we’ll create a sample database that we can use throughout this tutorial. To follow along and create your own, you’ll need to perform the following steps:

  • First, connect to your Mongo shell, then execute the command shown below:
> use employeeinfo
switched to db employeeinfo
  • Then, insert the following sample documents into the employee collection:
> db.employee.insertMany( [
...     { _id : "1001", name : "John", lastname : "prats", department : "ict", age : 20 },
...     { _id : "1002", name : "Anthony", lastname : "Nord", department : "training", age : 43},
...     { _id : "1003", name : "Kristine", lastname : "Vera", department : "training", age : 35 },
...     { _id : "1004", name : "Bernard", lastname : "Paddington", department : "QA", age : 27 },
...     { _id : "1005", name : "Kelvin", lastname : "Tejada", department : "ict", age : 30 },
...     { _id : "1006", name : "Willie", lastname : "Nickston", department : "training", age : 35 },
...     { _id : "1007", name : "Judie", lastname : "Megan", department : "Marketing", age : 40 },
...     { _id : "1008", name : "Sarah", lastname : "McBeth", department : "QA", "age" : 35 },
...     { _id : "1009", name : "Leila", lastname : "Landers", department : "Marketing", age : 35 },
...     { _id : "1011", name : "Daniel", lastname : "Mason", department : "training", age : 36 }
... ] );
{
        "acknowledged" : true,
        "insertedIds" : [
                "1001",
                "1002",
                "1003",
                "1004",
                "1005",
                "1006",
                "1007",
                "1008",
                "1009",
                "1011"
        ]
}
>

To verify that the insert process was successful, we can display the employee collection using the following command:

> db.employee.find()
{ "_id" : "1001", "name" : "John", "lastname" : "prats", "department" : "ict", "age" : 20 }
{ "_id" : "1002", "name" : "Anthony", "lastname" : "Nord", "department" : "training", "age" : 43 }
{ "_id" : "1003", "name" : "Kristine", "lastname" : "Vera", "department" : "training", "age" : 35 }
{ "_id" : "1004", "name" : "Bernard", "lastname" : "Paddington", "department" : "QA", "age" : 27 }
{ "_id" : "1005", "name" : "Kelvin", "lastname" : "Tejada", "department" : "ict", "age" : 30 }
{ "_id" : "1006", "name" : "Willie", "lastname" : "Nickston", "department" : "training", "age" : 35 }
{ "_id" : "1007", "name" : "Judie", "lastname" : "Megan", "department" : "Marketing", "age" : 40 }
{ "_id" : "1008", "name" : "Sarah", "lastname" : "McBeth", "department" : "QA", "age" : 35 }
{ "_id" : "1009", "name" : "Leila", "lastname" : "Landers", "department" : "Marketing", "age" : 35 }
{ "_id" : "1011", "name" : "Daniel", "lastname" : "Mason", "department" : "training", "age" : 36 }
>

MongDB itcount() and count() Example

Now that we’ve created a sample dataset, let’s take a look at some examples of the MongoDB itcount() and count() methods.

MongoDB itcount()

The MongoDB itcount() method is equivalent to the cursor.count() method, which is used to execute a query to an already existing cursor. It will return the count of the remaining documents in a cursor object. The basic form of the itcount() method is :

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

NOTE: the_query represents the criteria that need to be satisfied upon retrieving a document from a given collection.

MongDB itcount() Example

Next, we’ll look at an example of the itcount() method that will count the documents where the ‘department’ field has a value of ‘training’:

  db.employee.find( { "department" : "training"} ).itcount();

The output should look like this:

> db.employee.find( { "department" : "training"} ).itcount();
4

We can see that the method returned ‘4’.

NOTE: This method should not be used in conjunction with find() as it will throw an exception.

> db.employee.itcount( { "department" : "training"} );
2020-01-03T21:19:08.457+0800 E  QUERY    [js] uncaught exception: TypeError: db.employee.itcount is not a function :
@(shell):1:1

MongoDB count()

The MongoDB count() method simply returns the count of documents matching the criteria provided to the find() query.

The basic form of the count() method is:

 db.collection_name.find(<the_query>).count()

or

db.collection.count()

NOTE: the_query indicates the criteria that need to be satisfied upon retrieving a document from a given collection.

MongoDB count() Example

In this section, we’ll look at an example of how to use the count() method in the Mongo shell.

The basic syntax for the count() method is shown below:

> db.employee.count()
10

In this example, the command counts the number of documents in the ’employee’ collection.

Now, let’s step up our query a bit with the following command:

> db.employee.find({"department" : "training"}).count();
4
>

The code shown above will count the documents where ‘department’ field has a value of ‘training’.

Conclusion

Being able to count the number of documents that match certain criteria is an important skill to have when you’re working with data in MongoDB. The count() and itcount() methods make it easy to obtain this information. This article provided an overview of the MongoDB itcount() and count() methods and offered examples of using each one. With our instructions and examples, you’ll be prepared to use these methods in your own MongoDB environment.

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.