【发布时间】:2019-09-08 17:16:55
【问题描述】:
这是我的一个示例订单文档
{startDate: “2010:10:10”, numberOfHours: 10},
{startDate: “2010:11:10”, numberOfHours: 5},
{startDate: “2011:12:10”, numberOfHours: 1},
{startDate: “2012:10:10”, numberOfHours: 10}
首先,我想计算 startDate 每一年的订单数(totalOrders)并计算 numberOfHours(totalHours) 的总和。然后对于一年中的每个月,我需要计算订单数(订单)并计算 numberOfHours(小时)的总和。输出应如下所示
[
// Current year first
{
year: 2019,
totalOrders: 120,
totalHours: 1234,
months: [
{
month: 0, // 0 based month index so jan = 0
orders: 12,
hours: 120
},
{
month: 1,
orders: 5,
hours: 100
}
////////////
]
},
// 2018 etc
]
我查看了嵌套的 @group 示例,但找不到匹配项。我知道如何按如下方式分组年份和月份
const result = await this._collection.aggregate([
{
$project: {
startYear: { $substr: ["$startDate", 0, 4] },
startMonth: { $substr: ["$startDate", 5, 2] }
}
},
{
$group: {
_id: { year: "$startYear", month: "$startMonth" },
orders: { $sum: 1 },
hours: { $sum: "$numberOfHours" }
},
},
]).toArray();
知道如何继续我提到的输出吗? 任何帮助将不胜感激。
【问题讨论】:
标签: mongodb mongodb-query aggregation-framework