mongodb - 使用 ISODate 优化 $group 查询
问题描述
我必须得到花费最大成本的月份和年份。我使用$group
按年/月日期格式对它们进行分组。
db.times.aggregate(
[{
$group: {
_id: {
$dateToString: {
format: "%Y/%m",
date: "$date"
}
},
total_cost: {
$sum: "$cost_spent"
}
}
}, {
$sort: {
"total_cost": -1
}
}, {
$limit: 1
}])
两个问题:
有没有更快的方法来解析我的 ISODate$date
并将其部分用作$group
_id
?(试过了$month
,$year
他们更慢。)
有没有办法告诉$group
它$date
已排序(例如由于索引)?
解决方案
$substr
将季度/年月值分成 ayearSubstring
和 a的运算符yearMonthSubstring
:ISODate("2019-01-01T18:30:00Z")
-
db.times.aggregate(
[{
$group: {
_id: {
$substr: ['$date', 0, 7]
},
total_cost: {
$sum: "$cost_spent"
}
}
}, {
$sort: {
"total_cost": -1
}
}, {
$limit: 1
}])
推荐阅读
- vba - 计算一个值在列中出现的次数并将该值返回到不同的工作表
- http - 如何在 Apollo GraphQl 中传递多个标头
- c# - 如何将此表达式转换为 LINQ
- javascript - toDoList 和搜索添加的项目后的问题,当输入为空时应该回到上一个索引位置
- powershell - 使用 Powershell 枚举 Azure 存储帐户
- angular - Dart Web “传递库具有此平台不支持的 sdk 依赖项”
- pandas - 滚动日期范围内的价格变化百分比
- reactjs - 侧边栏中的动态和非动态路由
- javascript - 带有 Webpack 3.7 的 Angular 8 渲染速度极慢
- amazon-web-services - 为什么我在 AWS 中当前登录的用户没有 IAM 用户?