運算子 $stddevsamp 會透過取得欄位值的指定樣本來計算標準差。 標準差是通過隨機抽取指定大小的樣本來計算的。 如果需要精確的標準差,則必須改用$stdDevPop。
語法
{
$stddevsamp: {fieldName}
}
參數
| 參數 | Description |
|---|---|
fieldName |
其值用來計算指定樣本大小標準差的欄位 |
範例
請參考商店集合中的此範例檔。
{
"_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4",
"name": "First Up Consultants | Beverage Shop - Satterfieldmouth",
"location": {
"lat": -89.2384,
"lon": -46.4012
},
"staff": {
"totalStaff": {
"fullTime": 8,
"partTime": 20
}
},
"sales": {
"totalSales": 75670,
"salesByCategory": [
{
"categoryName": "Wine Accessories",
"totalSales": 34440
},
{
"categoryName": "Bitters",
"totalSales": 39496
},
{
"categoryName": "Rum",
"totalSales": 1734
}
]
},
"promotionEvents": [
{
"eventName": "Unbeatable Bargain Bash",
"promotionalDates": {
"startDate": {
"Year": 2024,
"Month": 6,
"Day": 23
},
"endDate": {
"Year": 2024,
"Month": 7,
"Day": 2
}
},
"discounts": [
{
"categoryName": "Whiskey",
"discountPercentage": 7
},
{
"categoryName": "Bitters",
"discountPercentage": 15
},
{
"categoryName": "Brandy",
"discountPercentage": 8
},
{
"categoryName": "Sports Drinks",
"discountPercentage": 22
},
{
"categoryName": "Vodka",
"discountPercentage": 19
}
]
},
{
"eventName": "Steal of a Deal Days",
"promotionalDates": {
"startDate": {
"Year": 2024,
"Month": 9,
"Day": 21
},
"endDate": {
"Year": 2024,
"Month": 9,
"Day": 29
}
},
"discounts": [
{
"categoryName": "Organic Wine",
"discountPercentage": 19
},
{
"categoryName": "White Wine",
"discountPercentage": 20
},
{
"categoryName": "Sparkling Wine",
"discountPercentage": 19
},
{
"categoryName": "Whiskey",
"discountPercentage": 17
},
{
"categoryName": "Vodka",
"discountPercentage": 23
}
]
}
]
}
範例 1 - 計算總銷售額的標準差
此查詢會透過隨機取樣符合篩選準則的 10 個文件,來計算「Fourth Coffee」公司中商店之間總銷售額的標準差。
db.stores.aggregate([{
$match: {
"company": "Fourth Coffee"
}
}, {
$sample: {
size: 10
}
}, {
$group: {
_id: "$company",
stdDev: {
$stdDevSamp: "$sales.totalSales"
}
}
}])
此查詢會傳回下列結果:
[
{
"_id": "Fourth Coffee",
"stdDev": 22040.044055209048
}
]