更好地分组Mongoose Aggregate查询

时间:2016-11-05 22:10:01

标签: javascript node.js mongodb mongoose

关于我的收藏结构的一些背景信息。我有各种类型的金融交易,都使用discriminatorKey保存到一个集合中。这是一个例子:

 "_id" : ObjectId("5816346ef201a84e17a84899"),
    "accountUpdatedBy" : -9.95,
    "transactionAmount" : 9.95,
    "paidTo" : "Vimeo",
    "expenseCategory" : "advertising",
    "accountName" : "Bank Name",
    "transactionDate" : ISODate("2016-08-31T00:00:00Z"),
    "transactionID" : "",
    "transactionComment" : "",
    "transactionCategory" : "SelfEmploymentExpense",
    "transactionFee" : 0,
    "entryDate" : ISODate("2016-10-30T17:57:02.144Z"),
    "__v" : 0

我需要做的是收集所有交易类型的总计,按年和月分组。在看了一些类似的问题之后,这是我提出的最好的问题:

Transaction.findTransactionCategoryTotalsByMonth = function () {
return this
    .aggregate([
        {$group: {
            _id: {transactionCategory: "$transactionCategory", month: {$month: "$transactionDate"}, year: {$year: "$transactionDate"}},
            total: {$sum: "$transactionAmount"},
        }},
        {$project: {
            year: "$_id.year",
            month: "$_id.month",
            transactionCategory: "$_id.transactionCategory",
            total: "$total",
            _id: false,
        }}
    ])
    .sort({year: 1, month: 1, transactionCategory: 1});
};

然而,这会产生如下结果:

 [ { total: 0,
    year: 2016,
    month: 8,
    transactionCategory: 'AccountUpdate' },
  { total:100,
    year: 2016,
    month: 8,
    transactionCategory: 'Other' },
  { total: 100,
    year: 2016,
    month: 8,
    transactionCategory: 'SelfEmploymentExpense' },
  { total: 100,
    year: 2016,
    month: 8,
    transactionCategory: 'SelfEmploymentIncome' },
  { total: 0,
    year: 2016,
    month: 9,
    transactionCategory: 'AccountUpdate' },
  { total: 100,
    year: 2016,
    month: 9,
    transactionCategory: 'CreditCardPayment' },
  { total: 100,
    year: 2016,
    month: 9,
    transactionCategory: 'Other' },
  { total: 100,
    year: 2016,
    month: 9,
    transactionCategory: 'SelfEmploymentExpense' } ]

问题非常清楚。理想情况下,我想找到一种方法来合并数据,以减少格式化响应时的迭代。允许我嵌套的东西,以便结束看起来像的结果:

    [{year: 2016, 
    SomeTransactionType: [100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100], // Amounts for each month in an array
    OtherTransactionType: [100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100]}]

或者通过更多嵌套来减少对象数量的任何其他方式。

非常感谢任何建议。如果这是基本的话,请提前道歉,因为我对JavaScript和编程一般都很陌生。

1 个答案:

答案 0 :(得分:0)

试试这个

`

Transaction.findTransactionCategoryTotalsByMonth = function () {
return this
    .aggregate([
        {$group: {
            _id: {year: {$year: "$transactionDate"},transactionCategory: "$transactionCategory"},
            total: {$push: "$transactionAmount"},
        }},
    {$group: {
            _id: "_id.year",
transactionCategoryArray : {$addToSet:{transactionCategory: "$_id.transactionCategory",transactionAmount:"$total"}}
      }},{$sort:{_id:-1}}
    ])
};

`