2016-11-05 6 views
1

내 컬렉션 구조에 대한 약간의 배경 정보. 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]}] 

이상의 중첩로, 아래로 개체의 수를 얻기의 다른 방법 :처럼 보이는 결과를 종료하기 위해 둥지에 나를 수있는 것이 무엇인가.

조언에 대해 매우 감사드립니다. 자바 스크립트와 프로그래밍 전반에 처음으로 익숙해지기 때문에 사전에 사과해야합니다.

답변

0

다음과 같이 시도해 볼 수 있습니다. 먼저 각 월 합계의 합계를 구하고, 정렬을 따르고, 두 번째 그룹화를 통해 각 카테고리의 모든 월 합계를 푸시하고, 최종 그룹화를 통해 각 월의 합계를 구합니다.

aggregate([{ 
     $group: { 
      _id: { 
       transactionCategory: "$transactionCategory", 
       month: { 
        $month: "$transactionDate" 
       }, 
       year: { 
        $year: "$transactionDate" 
       } 
      }, 
      monthTotal: { 
       $sum: "$transactionAmount" 
      } 
     } 
    }, { 
     $sort: { 
      year: 1, 
      month: 1, 
      transactionCategory: 1 
     } 
    }, { 
     $group: { 
      _id: { 
       transactionCategory: "$_id.transactionCategory", 
       year: "$_id.year" 
      }, 
      yearTotal: { 
       $push: "$monthTotal" 
      }, 
     } 
    }, { 
     $group: { 
      _id: { 
       year: "$_id.year" 
      }, 
      categoryTotal: { 
       $push: { 
        transactionCategory: "$_id.transactionCategory", 
        yearTotal: "$yearTotal" 
       } 
      } 
     } 
    }, { 
     $project: { 
      _id: 0, 
      year: "$_id.year", 
      categoryTotal: "$categoryTotal" 
     } 
    }]) 

샘플 출력

{ 
    "categoryTotal": [{ 
     "transactionCategory": "donating", 
     "yearTotal": [15.95] 
    }, { 
     "transactionCategory": "campaigning", 
     "yearTotal": [10.95] 
    }, { 
     "transactionCategory": "advertising", 
     "yearTotal": [12.95, 21.9] 
    }], 
    "year": 2016 
} 
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}} 
    ]) 
}; 

`

시도