首页 > 解决方案 > 使用 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已排序(例如由于索引)?

标签: mongodbaggregation-framework

解决方案


$substr将季度/年月值分成 ayearSubstring和 a的运算符yearMonthSubstringISODate("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
}])

推荐阅读