运算符 $covariancePop 对分区中的一个或多个字段的文档进行排序,并计算指定文档窗口中两个数值字段的协变。
Syntax
{
$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
}
]
相关内容
- 查看用于 从 MongoDB 迁移到 Azure DocumentDB 的选项。
- 详细了解 与 MongoDB 的功能兼容性。