2016-03-28 99 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操作對「產品」數組進行非規格化。從那裏你需要兩個$group階段。在第一小組階段,您將您的文檔按_id分組,您的情況必須是複合字段,並使用累加器運算符$sum返回價格總和。在最後的$group階段,您使用累加器運算符$push返回「產品」數組。

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" } } 
    }} 
]) 

將返回:

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

一個加法。將'{$ project:{_ id:0,customer:「$ _ id」,product:1}}'追加到聚合管道以符合OP所需的格式。 – Saleem

+0

@Saleem不!增加'$ project'會導致性能下降。 – styvane