2016-12-08 12 views
0

私はSQLバックグラウンドを持ち、mongodbのデータを集約する構文を理解していますが、MongoDBの複数のキー集約の出力を「平坦化」するのに問題があります。例えば、標準の構文は以下の通りです:mongodb複数のキー集約

db.transactions.aggregate(
    [ 
    { $group: { _id: {"category":"$category","postdate":"$postdate"} , "total": { $sum: "$total" } } } 
    ] 
); 

しかし、これは次の形式でデータを返します。

[{"_id":{"category":"Fees","postdate":"2013-01-04T05:00:00.000Z"},"total":24}, 
{"_id":{"category":"Fees","postdate":"2012-12-20T05:00:00.000Z"},"total":-0.02}] 

私は何をしたいことは私は次のような形式のデータであります

オプション1:依然として二つ以上の列にグループ化

[{"_id":"Auto","postdate":"2013-01-04T05:00:00.000Z","total":24}, 
{"_id":"Fees","postdate":"2012-12-20T05:00:00.000Z","total":-0.02}] 

オプション2:

["category":"Auto","postdate":"2013-01-04T05:00:00.000Z","total":24}, 
{"category":"Fees","postdate":"2012-12-20T05:00:00.000Z","total":-0.02}] 

mongodbでこれを行うにはどうすればよいですか?

+0

オプション1つの最初の行は、 '手数料' でなければなりません。それはタイプミスですか? – Veeram

+0

2番目の数字は実際には「自動」にする必要はありません。それを変更しました。ありがとう。 –

+0

私はそれを理解していません。カテゴリだけが変わると思っていますか?サンプル文書を含めることはできますか?カテゴリ別にグループ化し、集計に投稿日を続けます。カテゴリ別にグループ化するには、さらにグループステージが必要です。 – Veeram

答えて

2

フォーマット$project

オプション1使用して、あなたの応答:

db.transactions.aggregate(
     [ 
     { $group: { _id: {"category":"$category","postdate":"$postdate"} , "total": { $sum: "$total" } } }, 
     { $project: { "_id":0, "_id":"$_id.category", "postdate":"$_id.postdate", "total":1 } } 
     ] 
); 

オプション2:

db.transactions.aggregate(
     [ 
     { $group: { _id: {"category":"$category","postdate":"$postdate"} , "total": { $sum: "$total" } } }, 
     { $project: { "_id":0, "category":"$_id.category", "postdate":"$_id.postdate", "total":1 } } 
     ] 
);