2016-03-28 23 views
0

İç içe dizi öğesi kendisini Mongodb içinde toplayabilir mi? Örneğin. Ham veriaggregation nested Dizi elemanının kendisi 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}]} 
iç içe dizi elemanının her istiyoruz

müşteri tarafından tipine göre toplanır ör

Sonuç:

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

nasıl yaptığını bana göstermek için yardım eder misiniz? Teşekkürler.

cevap

2

Bunu, toplama çerçevesini kullanarak yapabilirsiniz. $unwind işlemini kullanarak "ürün" dizisini denormalize etmeniz gerekir. Oradan iki $group aşamasına ihtiyacınız var. İlk grup aşamasında, belgelerinizi bir bileşik alan olması gereken _id ile gruplandırırsınız ve fiyat toplamını döndürmek için $sum akümülatör operatörünü kullanın. Son $group aşamasında "ürün" dizisini döndürmek için $push akümülatör operatörünü kullanırsınız.

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

Bir eklenmesini: döndüren

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

. İstenen formatla uyumlu hale getirmek için toplama hattına {$ project: {_ id: 0, müşteri: "$ _ id", ürün: 1}} 'ekleyin. – Saleem

+0

@Saleem No! '$ project' ekleme, performans düşüşüne neden olur. – styvane