聚合嵌套数组元素本身在mongodb中

时间:2016-03-28 10:54:23

标签: mongodb mongodb-query aggregation-framework

是否可以在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}]}

你能帮忙告诉我怎么做吗?感谢。

1 个答案:

答案 0 :(得分:2)

您可以使用聚合框架执行此操作。您需要使用$unwind操作对“product”数组进行非规范化。从那里你需要两个$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
                }
        ]
}