$stdDevPop

The `$stdDevPop` operator calculates the standard deviation of the specified values. The operator can only calculate the standard deviation of numeric values.

Syntax

{
  $stdDevPop: <fieldName>
}

Parameters

fieldNamestringrequired

The field whose values are used to calculate the standard deviation.

Examples

Sample Data

{
  "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4",
  "name": "First Up Consultants | Beverage Shop",
  "sales": {
    "totalSales": 75670,
    "salesByCategory": [
      { "categoryName": "Wine Accessories", "totalSales": 34440 }
    ]
  }
}

Calculate the standard deviation of total sales

Calculate the standard deviation of total sales for all stores belonging to Fourth Coffee.

This query filters on the company field and calculates the standard deviation using $stdDevPop.

Query:

db.stores.aggregate([
  {
    $match: { company: "Fourth Coffee" }
  },
  {
    $group: {
      _id: "$company",
      stdDev: {
        $stdDevPop: "$sales.totalSales"
      }
    }
  }
])

Output:

[
  {
    "_id": "Fourth Coffee",
    "stdDev": 39133.27057120701
  }
]

Calculate the standard deviation of a field with a single value

When a field has only one distinct value, the standard deviation is 0.

This query groups by store name, where each store has a single value for total sales.

Query:

db.stores.aggregate([
  {
    $match: { company: "Fourth Coffee" }
  },
  {
    $group: {
      _id: "$name",
      stdDev: {
        $stdDevPop: "$sales.totalSales"
      }
    }
  }
])

Output:

[
  { "_id": "Fourth Coffee | Outdoor Equipment Collection", "stdDev": 0 },
  { "_id": "Fourth Coffee | Grocery Hub", "stdDev": 0 },
  { "_id": "Fourth Coffee | Pet Supply Nook", "stdDev": 0 }
]

Related