MongoDB $collStats Stage

Beginner
5 min read
Updated: Oct 2026
3 examples
Live preview

What Is $collStats?

$collStats is a MongoDB aggregation stage that reports statistics about the collection itself—size, document count, indexes, and optional latency metrics. It does not transform your business documents.

Remember
$collStats = "how big / busy is this collection?"

db.orders.aggregate([
  { $collStats: { storageStats: {} } }
])

must be the FIRST stage
storageStats → size, indexes, avgObjectSize
count → fast metadata total
latencyStats → read/write latency
scale: 1024 → sizes in KB

Quick shell check → db.orders.stats()
UsePrefer
Storage / index sizes in a pipeline$collStats
Exact filtered document totals$count
Per-index usage (ops since restart)$indexStats

How to Use $collStats in MongoDB

Put it first, pick the stats sections you need, then trim with $project.

  1. Start the pipeline with $collStats (nothing before it).
  2. Enable sections: storageStats, count, latencyStats, and/or queryExecStats.
  3. Optional: set storageStats.scale (e.g. 1024 for KB).
  4. Follow with $project to keep only the fields your dashboard needs.
OptionRequired?Role
storageStatsNoData size, avg doc size, index sizes
countNoFast metadata document total
latencyStatsNoRead/write latency (+ optional histograms)
queryExecStatsNoCollection scan counts

Pseudocode

Pseudocode
assert: $collStats is stage 1

result = {
  ns, host, localTime
}

if storageStats enabled:
  result.storageStats = { size, count, indexSizes, … }
  apply scale if provided

if count enabled:
  result.count = metadataDocumentCount

if latencyStats enabled:
  result.latencyStats = { reads, writes, … }

emit result   // one doc (or one per shard)

Cheat Sheet

Keep these facts handy while building admin and monitoring pipelines.

TopicDetail
TypeAggregation stage (collection diagnostics)
PositionMust be first in the pipeline
Common fieldsns, host, localTime + requested stats
Index sizesstorageStats.indexSizes, totalIndexSize
ScalestorageStats: { scale: 1024 } → KB
ShardedOne result document per shard
Shell helperdb.collection.stats()

Live Preview

Pick which stats sections to enable and see a simplified result shape (teaching model—sizes are sample values).

Collection: orders (5 docs, _id + customerId indexes).

Result
ns: "test.orders"
storageStats.count: 5
storageStats.size: 1234          // bytes
storageStats.nindexes: 2
storageStats.totalIndexSize: 8192

Worked Walkthrough — Storage Snapshot

Five orders and two indexes (_id + customerId). Goal: ask for storageStats and read size + count.

Calculation
Pipeline:
  1. $collStats { storageStats: {} }   ← must be first
  2. $project key fields (optional)

MongoDB looks up collection metadata (not each order row)

Sample fields you care about:
  storageStats.count          → 5
  storageStats.size           → data bytes
  storageStats.nindexes       → 2
  storageStats.totalIndexSize → index bytes

You asked “how big is orders?” — not “list the orders.”

MongoDB Examples

We use a small orders collection. First inspect storage, then get a fast count with KB-scaled sizes. Run these in mongosh after inserting the sample data once.

Example 1 — Sample Data

Seed five orders and one secondary index so storage and count stats have something meaningful to report.

mongosh
db.orders.drop()
db.orders.createIndex({ customerId: 1 })
db.orders.insertMany([
  { customerId: "C001", product: "Keyboard", amount: 45,  status: "shipped" },
  { customerId: "C002", product: "Mouse",    amount: 25,  status: "pending" },
  { customerId: "C001", product: "Monitor",  amount: 220, status: "shipped" },
  { customerId: "C003", product: "Webcam",   amount: 60,  status: "pending" },
  { customerId: "C002", product: "Headset",  amount: 80,  status: "shipped" }
])

How the Data Is Stored in MongoDB

After the insert, MongoDB keeps five documents in orders. Run find() to see them:

mongosh
db.orders.find()

Read the important fields like this:

FieldExamplePlain English
customerId"C001"Indexed customer key
product"Keyboard"Item ordered
amount45Order total

How It Works

  1. Reset the collection. drop() starts clean for repeatable demos.
  2. Add an index. customerId gives storageStats a second index to measure.
  3. Insert five orders. Small sample—enough for count and size fields to be non-zero.

Example 2 — storageStats

Goal: get collection size, document count, and index totals, then keep only the fields a dashboard needs.

mongosh
db.orders.aggregate([
  { $collStats: { storageStats: {} } },
  {
    $project: {
      ns: 1,
      host: 1,
      count: "$storageStats.count",
      dataSize: "$storageStats.size",
      avgDoc: "$storageStats.avgObjectSize",
      indexes: "$storageStats.nindexes",
      totalIndexSize: "$storageStats.totalIndexSize"
    }
  }
])

How It Works

  1. First stage only. $collStats must lead the pipeline.
  2. Enable storage. storageStats: {} fills size and index fields (bytes by default).
  3. Trim with $project. Keep the metrics you care about; drop WiredTiger noise.
  4. Note: Exact byte values vary by engine and version; the field names stay the same.

Example 3 — Count + Scale

Goal: get a fast metadata count, and report storage sizes in kilobytes with scale: 1024.

mongosh
// Count only — lightweight
db.orders.aggregate([
  { $collStats: { count: {} } }
])
// → { ns, host, localTime, count: 5 }

// Storage in kilobytes + count together
db.orders.aggregate([
  {
    $collStats: {
      storageStats: { scale: 1024 },
      count: {}
    }
  },
  {
    $project: {
      count: 1,
      dataSizeKB: "$storageStats.size",
      indexSizeKB: "$storageStats.totalIndexSize",
      scaleFactor: "$storageStats.scaleFactor"
    }
  }
])

How It Works

  1. Count alone. count: {} is a quick metadata total—not a full collection scan of each doc.
  2. Scale sizes. scale: 1024 divides reported sizes so dashboards show KB.
  3. Combine options. One $collStats object can enable storage and count together.
  4. Exact filtered totals? Prefer $count after a $match.

Edge Cases & Pitfalls

Check these before putting $collStats in admin pipelines.

order

Must be the first stage

Any stage before $collStats fails. Put filters and projections after it.

views

Views limit which options work

storageStats, count, and queryExecStats error on views. Run storage stats on the base collection.

shard

Sharded counts can be approximate

You get one stats document per shard. For exact filtered totals, use $count or countDocuments.

txn

Not allowed in transactions

$collStats is a diagnostics stage—run it outside multi-document transactions.

Performance Notes

ApproachCostBest for
$collStats count / storageMetadata lookupHealth checks, capacity
$collStats + $projectSmaller payloadMonitoring APIs
$count after $matchPipeline over docsExact filtered totals

Prefer the lightest option set you need. Enable latencyStats / queryExecStats only when investigating performance—not on every health ping.

Key Takeaways

  • Role: inspect collection size and health, not transform rows.
  • Position: always the first stage in the pipeline.
  • Options: combine storageStats, count, and friends in one object.
  • Scale: use scale: 1024 for KB-friendly dashboards.

One line: $collStats answers “how big and busy is this collection?”

Frequently Asked Questions

$collStats returns statistics about the collection you aggregate on—storage size, document count, index sizes, optional latency histograms, and query execution metrics. It reports collection health, not transformed user documents.
Always first: db.orders.aggregate([{ $collStats: { storageStats: {} } }]). Any stage before $collStats causes an error.
All optional: storageStats (sizes and indexes), count (document total), latencyStats (read/write latency, optional histograms), and queryExecStats (collection scan counts). Combine them in one object.
Both expose collection statistics. $collStats runs inside aggregation so you can chain $project afterward. db.collection.stats() is a quick shell helper for ad-hoc checks.
Partially. storageStats, count, and queryExecStats error on views. latencyStats can work. For storage details, run $collStats on the underlying collection.
$collStats outputs one document per shard (each includes a shard field). Count values may be approximate—use $count or countDocuments when you need an exact total.

Next: $count

Count documents that reach a pipeline stage—perfect after $match.

$count tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful