Introduction to MongoDB collection.count() Method

MongoDB is a non-relational database with advantages such as high performance, scalability, and reliability. In MongoDB, the count() method can be used to count the number of documents in a collection that meet certain conditions.

The count() method is an aggregation function in MongoDB used to count the number of documents that meet specified conditions. In MongoDB 3.6 and above, it is recommended to use the countDocuments() method instead of count() because countDocuments() is more efficient and accurate.

Syntax

The syntax of the count() method is as follows:

db.collection.count(query, options)

Where query represents the query condition, which can be a document object or a query operator object, and options is an optional option parameter used to specify additional parameters, such as limiting result quantity or setting sort order.

Use Cases

The count() method is mainly used for the following scenarios:

  • Counting the number of documents in a collection that meet specified conditions.
  • Determining whether documents exist in a collection that meet specified conditions.
  • Calculating the number of documents in a collection.

Examples

Below are two examples of using the count() method.

Example 1

Suppose we have a collection named users that stores multiple user information documents. Now, we need to query the number of users whose age is greater than or equal to 18. We can use the count() method to achieve this.

db.users.count({ age: { $gte: 18 } })

After executing the above code, the result returned is the number of documents that meet the condition.

Example 2

Suppose we have a collection named products that stores multiple product information documents. Now, we need to query the number of products whose stock is greater than 0, and sort them by price from low to high. We can use the count() method in conjunction with the sort() method to achieve this.

db.products.count({ stock: { $gt: 0 } }).sort({ price: 1 })

After executing the above code, the result returned is the number of documents that meet the condition, sorted by price from low to high.

Conclusion

The count() method is one of the commonly used aggregation functions in MongoDB, which can be used to count the number of documents in a collection that meet specified conditions. Although the count() method has been replaced by the countDocuments() method in MongoDB 3.6 and above, it can still be used to achieve some simple scenarios.