具有由数据定义的元素名称的MongoDB聚合组

具有由数据定义的元素名称的MongoDB聚合组,mongodb,aggregation-framework,Mongodb,Aggregation Framework,我试图在Mongo中汇总以下内容: {"customer_id":1,"attribute":"test1","value":101} {"customer_id":1,"attribute":"test2","value":102} {"customer_id":2,"attribute":"test1","value":201} {"customer_id":2,"attribute":"test2","value":202} 致: 我已经非常接近使用$group和$push,但这仍然创建

我试图在Mongo中汇总以下内容:

{"customer_id":1,"attribute":"test1","value":101}
{"customer_id":1,"attribute":"test2","value":102}
{"customer_id":2,"attribute":"test1","value":201}
{"customer_id":2,"attribute":"test2","value":202}
致:

我已经非常接近使用$group和$push,但这仍然创建了一个数组而不是关联数组

{
    "$group": {
        "_id": "$customer_id",
        "attributes": {"$push":{"attribute":"$attribute","value":"$value"}}
    }
}

有什么方法可以做到这一点吗?

如果需要将名称设置为“动态”,则不能使用聚合框架来实现这一点。您可以显式地指定它们。您当前的方法通常是最好的方法,您可以在代码中重新塑造服务器的结果。如果服务器上确实需要此功能,则可以使用mapReduce。但那不会那么快。谢谢,我也这么怀疑。它类似于SQL中的透视,其中值变成列。我可以动态生成它,但也有问题。你想做什么?我能举个例子吗?
{
    "$group": {
        "_id": "$customer_id",
        "attributes": {"$push":{"attribute":"$attribute","value":"$value"}}
    }
}