【问题标题】:How do I return group results by multiple fields in MongoDB?如何在 MongoDB 中按多个字段返回组结果?
【发布时间】: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


【解决方案1】:

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

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

当然没有 $match 阶段。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-05
    • 1970-01-01
    • 1970-01-01
    • 2018-07-17
    • 1970-01-01
    • 1970-01-01
    • 2021-11-20
    相关资源
    最近更新 更多