运算符 $derivative 对分区中的一个或多个字段上的文档进行排序,并计算窗口中第一个和最后一个文档之间的字段更改的平均速率。
Syntax
{
$derivative: {
input: < expression >,
unit: < timeWindow >
}
}
参数
| 参数 | Description |
|---|---|
input |
用于计算范围速率的表达式或字段 |
unit |
变化率时间窗口 |
例子
请考虑商店集合中的这个示例文档。
{
"_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 - 计算总销售额的派生量
若要计算第一个 Up 顾问公司中每个商店的总销售额的派生量,请先运行一个查询来筛选公司,按其上次更新时间戳的升序对生成的文档进行排序,并计算结果集中第一个和当前文档之间的总销售额的派生(平均更改率)。
db.stores.aggregate([{
"$match": {
"company": {
"$in": [
"First Up Consultants"
]
},
"$and": [{
"lastUpdated": {
"$gt": ISODate("2024-12-01T03:06:24.180Z")
}
},
{
"lastUpdated": {
"$lt": ISODate("2025-12-01T03:55:17.557Z")
}
}
]
}
},
{
"$setWindowFields": {
"partitionBy": "$company",
"sortBy": {
"lastUpdated": 1
},
"output": {
"storeAverageSales": {
"$derivative": {
"input": "$sales.totalSales",
"unit": "week"
},
"window": {
"range": [
-1,
0
],
"unit": "week"
}
}
}
}
},
{
"$project": {
"lastUpdated": 1,
"storeAverageSales": 1
}
}
])
此查询返回以下结果:
[
{
"_id": "2cf3f885-9962-4b67-a172-aa9039e9ae2f",
"lastUpdated": "2025-06-11T10:48:01.291Z",
"storeAverageSales": 21554495.708753344
}
]
相关内容
- 查看用于 从 MongoDB 迁移到 Azure DocumentDB 的选项。
- 详细了解 与 MongoDB 的功能兼容性。