我有一个文档示例如下:
{
_id: ObjectId("5dfa4f7b9254a519a5c7f166"),
Date: "12/11/19",
Description: "Amazon",
Amount: 32.01,
DebitCredit: "debit",
Category: "Shopping",
Month: 12,
Day: 11,
Year: 2019,
Account_Name: "Gold Delta SkyMiles"
}...
这是我的查询:
db.checks.aggregate([
{ $match: { Category: "Shopping" } },
{ $project: { Year: 1, Month: 1, Category: 1, Amount: { $sum: "$Amount" } } },
{
$group: {
_id: {
Year: "$Year",
Month: "$Month",
Category: "$Category",
Amount: { $sum: "$Amount" }
}
}
},
{ $sort: { Year: 1, Month: 1 } }
]);
我正在寻找每年/每月组合的总数。我怎样才能做到这一点?
你快到了,你只需要稍微调整一下你的$group
阶段: 从文档中:
按指定的_id表达式和每个不同的分组对输入文档进行分组
因此,我们所要做的就是在_id
场之外取出amount
场。
{
$group: {
_id: {
Year: "$Year",
Month: "$Month",
},
Amount: { $sum: "$Amount" }
}
}
- 我删除了
category
因为它是多余的,但请随时将其添加回您的查询中。
编辑:
对于$sort
阶段,Year
和Month
字段在$group
之后不存在,这是其失败的原因。
在$group
阶段之后,您的文档的格式为:
{
_id: {Year: number, Month: number},
Amount: number
}
因此,只需将您的$sort
更改为:
{ $sort: { '_id.Year': 1, '_id.Month': 1 } }