How do you count the number of documents in a MongoDB collection?

QuestionsQuestions4 SkillsProYour First MongoDB LabOct, 21 2025
0247

To count the number of documents in a MongoDB collection, you can use the countDocuments() method or the count() method. However, countDocuments() is preferred for accuracy, especially in cases where documents may be added or removed during the counting process.

Using countDocuments()

This method counts the number of documents that match a specified query. If no query is provided, it counts all documents in the collection.

Syntax:

db.collection.countDocuments(query)

Example:

To count all documents in a collection named students:

db.students.countDocuments({})

To count documents that match a specific condition, for example, students older than 20:

db.students.countDocuments({ age: { $gt: 20 } })

Using count()

The count() method is also available but is considered deprecated in favor of countDocuments(). It provides a count of documents in a collection but may not be as accurate in certain scenarios.

Syntax:

db.collection.count(query)

Example:

To count all documents in the students collection:

db.students.count()

Summary

  • Use countDocuments() for accurate counts, especially with queries.
  • Use count() for a quick count, but be aware it may not be as reliable in all situations.

0 Comments

no data
Be the first to share your comment!