首页 > 解决方案 > 如何在 MongoDB 中按多个字段返回组结果?

问题描述

在 MongoDB 中, aggregate下面的查询给出了每个产品类别的平均价格,其中 business-name 是"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查询,但是否可以在单个查询中执行此操作?

标签: mongodbmongodb-queryaggregation-framework

解决方案


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

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

当然没有 $match 阶段。


推荐阅读