mongodb - 如何在 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
查询,但是否可以在单个查询中执行此操作?
解决方案
您需要同时按 productCategory 和 businessName 分组:
var group = { $group: {
_id: {category: "$productCategory", name: "$businessName"},
total: { $avg: "$price" }
}}
当然没有 $match 阶段。
推荐阅读
- java - 在哪种情况下 obj != null 在 Java 中抛出 java.lang.NullPointerException?
- php - CodeIgniter - 重定向到其他控制器时会话不起作用
- java - 如何计算特定字符串出现的次数
- firefox - 如何隐藏“不推荐使用 mozImageSmoothingEnabled”。Firefox 中的通知?
- docker - Docker 存储库不存在
- python - 使用 Python 代码执行 Google 搜索列表
- scala - Scala 无法在 Reader monad 实现中推断参数类型
- html - 带有 csl 的 bookdown::tufte_html_book 无法将引文放在边距中
- android - Flutter 返回 `lifecycle-common-java8.jar (androidx.lifecycle:lifecycle-common-java8:2.0.0)` 错误
- django - Django ManytoManyField 的限制选项