如何在MongoDB中按多个字段返回分组结果? [英] How do I return group results by multiple fields in MongoDB?
问题描述
在MongoDB中,下面的aggregate
查询给出每个产品类别的平均价格,其中业务名称为"Foobar Inc"
.
In MongoDB, the aggregate
query below gives the average price per product-category, where business-name is "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.".带有变量,以便返回多个平均价格.
However, I want to replace "FooBar Inc." with a variable, so that multiple average-prices are returned.
返回的数据将类似于:
鞋,Foobar Inc .:平均价格97
shoes, Foobar Inc.: average price 97
Foobar Inc.的玩具:平均价格88
toys, Foobar Inc.: average price 88
Quux Ltd.鞋:平均价格68
shoes, Quux Ltd.: average price 68
Quux Ltd.的玩具:平均价格101
toys, Quux Ltd.: average price 101
我可以运行多个aggregate
查询,但是在单个查询中是否可以执行此操作?
I could run multiple aggregate
queries, but is there away to do this in a single query?
推荐答案
您需要同时按productCategory和businessName进行分组:
You need to group by both productCategory and businessName:
var group = { $group: {
_id: {category: "$productCategory", name: "$businessName"},
total: { $avg: "$price" }
}}
当然没有$ match阶段.
and no $match stage of course.
这篇关于如何在MongoDB中按多个字段返回分组结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!