Introduction to MongoDB cursor.count() Method

The cursor.count() method is a MongoDB query method used to count the number of documents that match the query condition. The method returns a number that represents the count of documents that match the condition.

Syntax

db.collection.find().count(query, options)

The query parameter is the query condition, which is a JSON object. The options parameter is an optional parameter that is a JSON object used to specify some options.

Use Cases

The cursor.count() method is usually used to query the number of documents that meet the condition. In some scenarios, we may only be interested in the number of documents and not the documents themselves. In this case, we can use the cursor.count() method to avoid returning a large amount of document data.

Example

Assume there is an employees collection that contains the following documents:

{ "_id": 1, "name": "Alice", "age": 25 }
{ "_id": 2, "name": "Bob", "age": 30 }
{ "_id": 3, "name": "Charlie", "age": 35 }
{ "_id": 4, "name": "David", "age": 40 }

We can use the cursor.count() method to query the number of documents that meet the condition. For example, the following code queries the number of employees aged 30 or older:

const cursor = db.employees.find({ age: { $gte: 30 } })
const count = cursor.count()
print(`The number of employees aged 30 or older is: ${count}`)

The output is:

The number of employees aged 30 or older is: 3

Conclusion

The cursor.count() method is a MongoDB query method used to count the number of documents that match the query condition. Using this method can avoid returning a large amount of document data and only return the count of documents that meet the condition.