Introduction to MongoDB cursor.itcount() Method

cursor.itcount() is a method in MongoDB that returns the number of documents in the query result. This method is a member method of cursor, which can be used to iterate through the query result and return the number of documents. The itcount() method was introduced in MongoDB version 2.2.

Syntax

The syntax of the cursor.itcount() method is as follows:

cursor.itcount()

Usage

The cursor.itcount() method can be used in MongoDB to return the number of documents that satisfy the query condition. This method is typically used in the following scenarios:

  • In situations where it is necessary to know the number of documents in the query result, cursor.itcount() method can be used to obtain the number of documents;
  • If the number of documents in the query result is large, it may be necessary to obtain the data in batches. cursor.skip() and cursor.limit() methods can be used to obtain data in batches.

Example

Suppose we have a collection named users with the following documents:

{ "_id": 1, "name": "John", "age": 30 }
{ "_id": 2, "name": "Mary", "age": 25 }
{ "_id": 3, "name": "Peter", "age": 40 }
{ "_id": 4, "name": "David", "age": 35 }
{ "_id": 5, "name": "Lisa", "age": 27 }

Now, we want to query all users who are over 30 years old and return the number of documents. The following code can be used to achieve this:

const cursor = db.users.find({ age: { $gt: 30 } })
const count = cursor.itcount()
print(`There are ${count} documents in the query result.`)

After executing the above code, the following result will be output:

There are 2 documents in the query result.

Conclusion

The cursor.itcount() method is a convenient method that can be used in MongoDB to return the number of documents that satisfy the query condition. It can help developers quickly understand the number of documents in the query result. Meanwhile, when the query result contains a large number of documents, cursor.skip() and cursor.limit() methods can be used to obtain data in batches to avoid returning too much data at once.