Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/azure/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mongodb:如何在两个字段的断点处求和?_Mongodb_Aggregation Framework - Fatal编程技术网

Mongodb:如何在两个字段的断点处求和?

Mongodb:如何在两个字段的断点处求和?,mongodb,aggregation-framework,Mongodb,Aggregation Framework,我有一份文件样本如下: { _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" }...

我有一份文件样本如下:

{
  _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表达式和每个不同的分组对输入文档进行分组

因此,我们所要做的就是将
金额
字段从
\u id
字段中取出

{
    $group: {
      _id: {
        Year: "$Year",
        Month: "$Month",
      },
      Amount: { $sum: "$Amount" }
    }
}
  • 我删除了
    类别
    ,因为它是多余的,但可以随意将其添加回您的查询中
编辑:

对于
$sort
阶段,
字段在
$group
之后不存在,这是其失败的原因

$group
阶段后,您的文档的格式如下:

{
    _id: {Year: number, Month: number},
    Amount: number
}
因此,只需将您的
$sort
更改为:

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

这成功了!我在任何文档中都找不到,谢谢!(不过我的那一类还差呢)我把它加到了我的答案里。