2016-03-28 4 views
0

ネストされた配列要素自体をMongodbに集約することは可能ですか?例えば生データはアグリゲーションネストされた配列要素自体mongodb

{"transId" : "12345","customer" : "cust1", "product" : [{"type" : "cloth","price" : 100},{"type" : "toy","price" : 200}]} 
{"transId" : "45672","customer" : "cust1", "product" : [{"type" : "cloth","price" : 10},{"type" : "toy","price" : 500}]} 
{"transId" : "99999","customer" : "cust2", "product" : [{"type" : "cloth","price" : 40},{"type" : "toy","price" : 5}]} 

です。ネストされた配列要素のそれぞれは、顧客のタイプに応じて集計されます。

結果

{"customer" : "cust1", "product" : [{"type" : "cloth","price" : 110},{"type" : "toy","price" : 700}]} 
{"customer" : "cust2", "product" : [{"type" : "cloth","price" : 40},{"type" : "toy","price" : 5}]} 

あなたがそれを行う方法私を見るために助けてくださいもらえますか?ありがとう。

答えて

2

これは、集計フレームワークを使用して行うことができます。 $unwind操作を使用して、 "製品"配列を非正規化する必要があります。そこから2つの$groupステージが必要です。最初のグループステージでは、文書をグループ化して_idとすると、複合フィールドでなければなりません。$sumアキュムレータ演算子を使用して価格の合計を返します。最後の$groupステージでは、$pushアキュムレータ演算子を使用して、「製品」の配列を返します。

{ 
     "_id" : "cust1", 
     "product" : [ 
       { 
         "type" : "toy", 
         "price" : 700 
       }, 
       { 
         "type" : "cloth", 
         "price" : 110 
       } 
     ] 
} 
{ 
     "_id" : "cust2", 
     "product" : [ 
       { 
         "type" : "toy", 
         "price" : 5 
       }, 
       { 
         "type" : "cloth", 
         "price" : 40 
       } 
     ] 
} 
+0

一つ追加する:返す

db.customers.aggregate([ // Denormalize the product array { "$unwind": "$product" }, // Group your documents by '_id' { "$group": { "_id": { "customer": "$customer", "type": "$product.type" }, "price": { "$sum": "$product.price" } }}, // reconstruct the "product" array. { "$group": { "_id": "$_id.customer", "product": { "$push": { "type": "$_id.type", "price": "$price" } } }} ]) 

。 OPの希望のフォーマットに合致するように '{$ project:{_ id:0、customer:" $ _ id "、product:1}}'をアグリゲーションパイプラインに追加します。 – Saleem

+0

@Saleemいいえ! '$ project'を追加するとパフォーマンスが低下します。 – styvane

関連する問題