$stdDevSamp
The `$stdDevSamp` operator calculates the standard deviation by taking a specified sample of the values of a field. The standard deviation is calculated by taking a random sample of the specified size. If a precise standard deviation is needed, $stdDevPop must be used instead.
Syntax
{
$stdDevSamp: <fieldName>
}
Parameters
fieldName
stringrequiredThe field whose values are used to calculate the standard deviation of the specified sample size.
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 across stores by taking a random sample.
This query takes a sample of 10 documents matching the filtering criteria and calculates standard deviation.
Query:
db.stores.aggregate([
{
$match: { company: "Fourth Coffee" }
},
{
$sample: { size: 10 }
},
{
$group: {
_id: "$company",
stdDev: {
$stdDevSamp: "$sales.totalSales"
}
}
}
])
Output:
[
{
"_id": "Fourth Coffee",
"stdDev": 22040.044055209048
}
]