如何在MongoDB中按多个字段返回分组结果?

时间:2019-07-29 08:50:37

标签: mongodb mongodb-query aggregation-framework

在MongoDB中,下面的aggregate查询给出了每个产品类别的平均价格,其中商家名称为"Foobar Inc"

var match = { $match: {"businessName": "FooBar Inc"}, ;

var group = { $group: { _id: "$productCategory", total: { $avg: "$price" }}}

var results = await db.aggregate("productsCollection", limit, match, group);

来自productCollection的示例对象:

{"businessName": "FooBar Inc.",  "productCategory": "toys", "price":88}

输出:

 [{"_id": "shoes", "total":97}, {"_id": "toys", "total":77}]

但是,我想替换“ FooBar Inc.”。带有变量,以便返回多个平均价格。

返回的数据将类似于:

  

鞋子,Foobar Inc .:平均价格97

     

Foobar Inc.的玩具:平均价格88

     

Quux Ltd.鞋:平均价格68

     

Quux Ltd.的玩具:平均价格101

我可以运行多个aggregate查询,但是可以在单个查询中执行此操作吗?

1 个答案:

答案 0 :(得分:1)

您需要同时按productCategory和businessName进行分组:

var group = { $group: { 
    _id: {category: "$productCategory", name: "$businessName"}, 
    total: { $avg: "$price" }
}}

当然没有$ match阶段。