【问题标题】:How to aggregate and fetch a record from MongoDB?如何从 MongoDB 聚合和获取记录?
【发布时间】:2020-10-13 02:08:07
【问题描述】:

我正在学习 MongoDB 查询并尝试进行聚合。 如果我有如下记录列表:

{ _id: 1, cust_id: "abc1", ord_date: ISODate("2012-11-02T17:04:11.102Z"), status: "A", amount: 50 }
{ _id: 2, cust_id: "xyz1", ord_date: ISODate("2013-10-01T17:04:11.102Z"), status: "A", amount: 100 }
{ _id: 3, cust_id: "xyz1", ord_date: ISODate("2013-10-12T17:04:11.102Z"), status: "D", amount: 25 }
{ _id: 4, cust_id: "xyz1", ord_date: ISODate("2013-10-11T17:04:11.102Z"), status: "D", amount: 125 }
{ _id: 5, cust_id: "abc1", ord_date: ISODate("2013-11-12T17:04:11.102Z"), status: "A", amount: 25 }

如果我想根据status 对以上记录进行分组,并且需要根据最大amount 获取记录 所以我需要从上面的集合中输出两条记录:

_id:2 应该从 status: A 中获取,_id:4 应该从 status:D 组中获取。 有没有办法做到这一点?

我已经完成了示例中的示例查询,它们正在分组和计算总和或平均值,那么我们如何实现这一点。

【问题讨论】:

标签: mongodb aggregation-framework


【解决方案1】:

要对文档进行分组,您需要使用$group 运算符。

说明

  1. 我们在data里面存储相同状态的文档
  2. 我们应用$reduce 运算符来获取最大amount 值的文档

试试这个:

db.collection.aggregate([
  {
    $group: {
      _id: "$status",
      data: {
        $push: "$$ROOT"
      }
    }
  },
  {
    $replaceWith: {
      $reduce: {
        input: "$data",
        initialValue: {
          amount: -1
        },
        in: {
          $cond: [
            {
              $gt: [
                "$$this.amount",
                "$$value.amount"
              ]
            },
            "$$this",
            "$$value"
          ]
        }
      }
    }
  }
])

MongoPlayground | Alternative with $max

【讨论】:

    猜你喜欢
    • 2013-12-19
    • 1970-01-01
    • 2019-02-05
    • 2020-03-05
    • 2019-12-29
    • 1970-01-01
    • 2021-07-01
    • 1970-01-01
    相关资源
    最近更新 更多