Introduction to MongoDB cursor.size() Method
In MongoDB, the cursor.size()
method is used to return the number of documents that match a query.
Syntax
db.collection.find().size()
The method takes no parameters.
Use Cases
In some cases, we may want to know the number of documents that match a query. For example, we may need to know how many documents in a collection match a given query condition. In this case, we can use the cursor.size()
method.
Examples
Here are two examples of using the cursor.size()
method:
Assume we have a collection named employees
that contains employee records. To get the number of employees in the “Sales” department, we can use the following code:
const cursor = db.employees.find({ department: "Sales" })
const count = cursor.size()
print(`Number of employees in Sales department: ${count}`)
Output:
Number of employees in Sales department: 42
Assume we have a collection named orders
that contains order records. To get the number of orders with a status of “unprocessed”, we can use the following code:
const cursor = db.orders.find({ status: "unprocessed" })
const count = cursor.size()
print(`Number of unprocessed orders: ${count}`)
Output:
Number of unprocessed orders: 18
Conclusion
In MongoDB, the cursor.size()
method can be used to return the number of documents that match a query. It can be used to get the number of documents that match a given query condition, which is useful for understanding the size of a data collection and basic statistics.