How to Check Collection Size in MongoDB Quickly
To check the size of a collection in MongoDB, use the
db.collection.countDocuments() method to get the number of documents. For storage size details, use db.collection.stats() which returns the collection size in bytes and other useful info.Syntax
The main commands to check collection size are:
db.collection.countDocuments(): Returns the number of documents in the collection.db.collection.stats(): Returns detailed statistics includingsize(data size in bytes) andstorageSize(allocated storage size).
mongodb
db.collection.countDocuments() db.collection.stats()
Example
This example shows how to get the document count and the storage size of a collection named users.
mongodb
use myDatabase // Get number of documents in 'users' collection const count = db.users.countDocuments() print('Document count:', count) // Get collection stats including size const stats = db.users.stats() print('Collection size in bytes:', stats.size) print('Storage size in bytes:', stats.storageSize)
Output
Document count: 1500
Collection size in bytes: 245760
Storage size in bytes: 262144
Common Pitfalls
Common mistakes when checking collection size include:
- Using
count()which is deprecated and may give inaccurate results with filters. - Confusing
size(actual data size) withstorageSize(allocated space including padding). - Not switching to the correct database before running commands.
mongodb
/* Wrong: deprecated count() method */ db.users.count() /* Right: use countDocuments() for accurate count */ db.users.countDocuments()
Quick Reference
| Command | Description |
|---|---|
| db.collection.countDocuments() | Returns the number of documents in the collection. |
| db.collection.stats().size | Returns the total size of data in bytes. |
| db.collection.stats().storageSize | Returns the allocated storage size in bytes. |
| use databaseName | Switch to the database containing the collection. |
Key Takeaways
Use db.collection.countDocuments() to get the exact number of documents.
Use db.collection.stats() to get detailed size information including storage size.
Avoid using deprecated db.collection.count() for counting documents.
Remember to switch to the correct database before running commands.
Understand the difference between data size and storage size in stats.