[英]aggregation nested Array element itself in 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}]}
您能帮我示范一下吗? 谢谢。
您可以使用聚合框架执行此操作。 您需要使用$unwind
操作对“ product”数组进行非规范化。 从那里,您需要两个$group
阶段。 在第一个分组阶段,您按_id
对文档进行分组,在这种情况下,该_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
}
]
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.