【发布时间】:2019-07-29 17:45:01
【问题描述】:
在 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 查询,但是否可以在单个查询中执行此操作?
【问题讨论】:
-
你能从 productsCollection 添加示例对象吗?
-
我这样做了,也简化了输出
标签: mongodb mongodb-query aggregation-framework