The $collStats stage returns collection-level statistics—document count, storage footprint, index sizes, latency histograms, and collection scan metrics—ideal for monitoring dashboards and performance audits.
01
Storage stats
Size, indexes, avg doc.
02
Fast count
Metadata-based total.
03
Latency stats
Read/write histograms.
04
Query exec
Collection scan totals.
05
First stage
Pipeline must start here.
06
Sharded output
One doc per shard.
Fundamentals
Definition and Usage
$collStats is an aggregation stage that inspects the collection you run it on and returns diagnostic documents. Unlike stages that transform user data row-by-row, it reports server-side metrics about the collection itself.
💡
Beginner tip
Think of $collStats as db.collection.stats() inside a pipeline. Pick the sections you need—storageStats for disk/index size, count for a quick document total, latencyStats for slow-read investigation.
Use $collStats in admin pipelines, health checks, and capacity planning. Combine options in one stage, then follow with $project to trim fields for a monitoring API. Not allowed inside transactions.
Foundation
📝 Syntax
$collStats accepts an options object—all fields are optional but you typically enable at least one:
latencyStats helps spot slow collections. Histogram buckets show how many operations fell into each microsecond range—useful when tuning indexes after seeing high-latency tails.
Example 5 — Collection scan diagnostics
mongosh
// Unindexed query — may increment collection scan counter
db.orders.find({ notes: "rush order" }).toArray()
db.orders.aggregate([
{ $collStats: { queryExecStats: {} } },
{
$project: {
ns: 1,
collScans: "$queryExecStats.collectionScans.total",
nonTailableScans: "$queryExecStats.collectionScans.nonTailable"
}
}
])
/* High collectionScans.total → missing indexes or
queries that cannot use indexes. Add indexes or
rewrite queries, then compare over time. */
// Compare with db.collection.stats() shell helper:
db.orders.stats({ scale: 1024 })
📤 queryExecStats:
collectionScans.total → full collection scans
collectionScans.nonTailable → excluding tailable cursors
Rising counts → index tuning needed
How It Works
queryExecStats surfaces how often queries scanned entire collections— a red flag for performance. Use alongside the explain plan and index builds.
Compare
📋 $collStats vs related tools
Tool / stage
Effect
Best for
$collStats
Collection stats inside aggregation pipeline
Automated monitoring pipelines, $project trimming
db.collection.stats()
Direct shell stats call
Quick manual inspection in mongosh
$indexStats
Per-index usage since startup
Find unused indexes
$count
Exact document count in pipeline
Accurate totals (scans matching docs)
db.collection.countDocuments()
Accurate count query
When metadata count is not trusted
🧠 How $collStats Works
1
Pipeline starts on collection
$collStats runs as stage 1 against the target collection namespace.
Target
2
Server gathers metrics
MongoDB reads storage engine metadata, counters, and latency trackers for requested sections.
Collect
3
Stats document emitted
One doc (or one per shard) with ns, host, and enabled stat blocks.
Output
=
📊
Downstream stages process
Optional $project, $merge, or export to monitoring systems.
Important
📝 Notes
$collStats is not allowed in transactions.
After an unclean shutdown, size/count stats may be inaccurate until you run validate on the collection.
count from metadata is fast but can drift on sharded clusters—use $count or countDocuments() for precision.
On sharded collections, sum per-shard count values yourself for a cluster total.
Time series collections include extra storageStats.timeseries bucket diagnostics.
$collStats puts collection diagnostics inside your aggregation toolbox. Enable storageStats for capacity planning, latencyStats for slow-operation analysis, and queryExecStats to catch full collection scans.
For a quick shell check use db.collection.stats(); for automated pipelines use $collStats as stage one, then shape output with $project. Next: $count.
Request only the stat sections you need—smaller payloads, faster queries
Use scale: 1024 or 1048576 for KB/MB reporting
Follow with $project to build clean monitoring API responses
Track queryExecStats.collectionScans over time after index changes
On sharded clusters, aggregate per-shard results explicitly
❌ Don’t
Place any stage before $collStats
Trust metadata count alone for billing-critical exact totals
Run storageStats on views—it errors
Use inside multi-document transactions
Confuse cumulative latency stats (since startup) with per-query profiler data
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about $collStats
Use these points when monitoring MongoDB collections.
5
Core concepts
📊01
Collection stats
Size, count, indexes.
Basics
📚02
First stage
Pipeline rule.
Syntax
📈03
storageStats
Scale for KB/MB.
Storage
⏱️04
latencyStats
Histogram option.
Perf
🔍05
Coll scans
queryExecStats.
Tune
❓ Frequently Asked Questions
$collStats returns statistics about the current collection—storage size, document count, index sizes, optional latency histograms, and query execution metrics. It must be the first stage in an aggregation pipeline and is used for monitoring and performance tuning.
Always first: db.orders.aggregate([{ $collStats: { storageStats: {} } }]). If any stage appears before $collStats, MongoDB returns an error.
All optional: storageStats (sizes, indexes), count (document total), latencyStats (read/write latency with optional histograms), queryExecStats (collection scan counts). Combine them in one object: { $collStats: { storageStats: {}, count: {} } }.
Both expose collection statistics. $collStats runs inside an aggregation pipeline so you can chain $project or $merge afterward. db.collection.stats() is a direct shell helper—often simpler for quick checks.
Partially. storageStats, count, and queryExecStats return errors on views. latencyStats can work on views. For physical storage details, run $collStats on the underlying collection.
$collStats outputs one document per shard, each with a shard field. Count values come from per-shard metadata and may be approximate—use $count or countDocuments for exact totals when accuracy matters.
Did you know?
$collStats was introduced in MongoDB 3.2 for aggregation-based monitoring. On time series collections, storageStats.timeseries exposes bucket-level metrics like bucketCount and numCommits. See the official $collStats docs.