How do I return group results by multiple fields in MongoDB?

早过忘川 提交于 2019-12-11 15:53:41

问题


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);

Example object from productCollection:

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

Output:

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

However, I want to replace "FooBar Inc." with a variable, so that multiple average-prices are returned.

The data returned would be something like:

shoes, Foobar Inc.: average price 97

toys, Foobar Inc.: average price 88

shoes, Quux Ltd.: average price 68

toys, Quux Ltd.: average price 101

I could run multiple aggregate queries, but is there away to do this in a single query?


回答1:


You need to group by both productCategory and businessName:

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

and no $match stage of course.



来源:https://stackoverflow.com/questions/57250237/how-do-i-return-group-results-by-multiple-fields-in-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!