$covariancePop 運算子會對分割區內的一個或多個欄位進行文件排序,並在指定的文件視窗內計算兩個數值欄位的共變異數。
語法
{
$covariancePop: [ < numericalExpression1 > , < numericalExpression2 > ]
}
參數
| 參數 | Description |
|---|---|
numericalExpression1 |
要用於在指定文件視窗內計算共變異數的第一個數值運算式 |
numericalExpression2 |
要用於在指定文件視窗內計算共變異數的第一個數值運算式 |
範例
請參考商店集合中的此範例檔。
{
"_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 - 計算銷售量的共變異數
若要取得 First Up Consultants 公司的各商店總銷售額共變異數,首先執行查詢以篩選公司名稱,接著將結果文件依最後更新時間以升冪排序,然後計算排序結果中第一個文件與目前文件之間的共變異數。
db.stores.aggregate(
[{
"$match": {
"company": {
"$in": [
"First Up Consultants"
]
}
}
},
{
"$setWindowFields": {
"partitionBy": "$company",
"sortBy": {
"lastUpdated": 1
},
"output": {
"covariancePopForSales": {
"$covariancePop": [{
"$hour": "$lastUpdated"
},
"$sales.totalSales"
],
"window": {
"documents": [
"unbounded",
"current"
]
}
}
}
}
},
{
"$project": {
"company": 1,
"name": 1,
"sales.totalSales": 1,
"lastUpdated": 1,
"covariancePopForSales": 1
}
}
]
)
此查詢傳回的前兩個結果是:
[
{
"_id": "2cf3f885-9962-4b67-a172-aa9039e9ae2f",
"sales": {},
"company": "First Up Consultants",
"lastUpdated": "2025-06-11T10:48:01.291Z",
"name": "First Up Consultants | Bed and Bath Center - South Amir",
"covariancePopForSales": null
},
{
"_id": "8e7a259b-f7d6-4ec5-a521-3bed53adc587",
"name": "First Up Consultants | Drone Stop - Lake Joana",
"sales": {},
"company": "First Up Consultants",
"lastUpdated": {
"t": 1727827539,
"i": 1
},
"covariancePopForSales": null
}
]