マイコレクションの構造に関する背景情報。 discriminatorKeyを使用して、すべて1つのコレクションに保存されたさまざまな種類の金融取引があります。ここに例があります:モンゴーズ集約クエリのグループ化の改善
"_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
私がする必要があるのは、すべての取引タイプを合計して、年と月でグループ化したものです。
[ { 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' } ]
きれいであることの問題:しかし、これはこのような結果を生成
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});
};
:ここではいくつかの同様の質問を見てみたら、これは私が作ってみた最適なクエリであります明らかです。理想的には、レスポンスの書式設定時に反復を減らすために、データを少し統合する方法を探したいと思います。
[{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とプログラミング全般について非常に新しいので、これが基本的なものであれば事前にお詫びしておきます。