$collStats

The `$collStats` stage in the aggregation pipeline is used to return statistics about a collection. This stage provides detailed information that can help with database optimization and monitoring.

Syntax

{
  $collStats: {
    latencyStats: { histograms: <boolean> },
    storageStats: { scale: <number> },
    count: {}
  }
}

Parameters

latencyStatsobject

Optional. Specifies whether to include latency statistics. The histograms field indicates whether to include histograms of latency data.

storageStatsobject

Optional. Specifies whether to include storage statistics. The scale field is a number that indicates the scale factor.

countobject

Optional. Includes the count of documents in the collection.

Examples

Sample Data

{
  "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4",
  "name": "First Up Consultants | Beverage Shop",
  "sales": { "totalSales": 75670 }
}

Get collection statistics

Return statistics about the stores collection including storage and count information.

This query retrieves comprehensive collection statistics.

Query:

db.stores.aggregate([
  {
    $collStats: {
      storageStats: { scale: 1 },
      count: {}
    }
  }
])

Output:

[
  {
    "ns": "database.stores",
    "count": 45505,
    "storageStats": {
      "size": 123456789,
      "count": 45505
    }
  }
]

Related