Mongodb:如何在 2 个字段中的休息时间求和?



我有一个文档示例如下:

{
_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阶段,YearMonth字段在$group之后不存在,这是其失败的原因。

$group阶段之后,您的文档的格式为:

{
_id: {Year: number, Month: number},
Amount: number
}

因此,只需将您的$sort更改为:

{ $sort: { '_id.Year': 1, '_id.Month': 1 } }

最新更新