是否可以在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}]}你能帮我示范一下怎么做吗?谢谢。
发布于 2016-03-28 11:55:16
您可以使用聚合框架来完成这个任务。您需要使用$unwind操作对"product“数组进行去denormalize。从那里你需要两个$group阶段。在第一个组阶段,您按照_id (在您的情况下必须是一个复合字段)对文档进行分组,并使用$sum累加器操作符返回价格之和。在最后一个$group阶段,您使用$push累加器操作符返回一个"product“数组。
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
}
]
}https://stackoverflow.com/questions/36260835
复制相似问题