【问题标题】:Group by field(s) and aggregate on max date按字段分组并在最大日期聚合
【发布时间】:2017-06-02 17:24:02
【问题描述】:

我有mongo 类型的文档-

{
    "_id" : ObjectId("77f02ee61df85c423b6a4e79"),
    "client" : "1"
    "type" : "type1",
    "hierarchy" : "hier1",
    "creationDate" : ISODate("2015-09-09T13:06:44Z"),
    "model" : "m1"
},
{
    "_id" : ObjectId("77f02ee61df85c423b6a4e80"),
    "client" : "1"
    "type" : "type1",
    "hierarchy" : "hier1",
    "creationDate" : ISODate("2015-09-10T14:06:44Z"),
    "model" : "m2"
},
{
    "_id" : ObjectId("77f02ee61df85c423b6a4e81"),
    "client" : "1"
    "type" : "type1",
    "hierarchy" : "hier2",
    "creationDate" : ISODate("2015-09-10T13:06:44Z"),
    "model" : "m3"
},
{
    "_id" : ObjectId("77f02ee61df85c423b6a4e82"),
    "client" : "2"
    "type" : "type2",
    "hierarchy" : "hier2",
    "creationDate" : ISODate("2015-09-10T14:06:44Z"),
    "model" : "m4"
}

我想回答这个查询 - 对于给定的client,获取每个typehierarchy 组合(类型+层次结构)的所有最新(creationDate)文档。

例如。 client = 1 的上述数据集的输出将如下所示

 {
    "_id" : ObjectId("77f02ee61df85c423b6a4e80"),
    "client" : "1"
    "type" : "type1",
    "hierarchy" : "hier1",
    "creationDate" : ISODate("2015-09-10T14:06:44Z"),
    "model" : "m2"
},
{
    "_id" : ObjectId("77f02ee61df85c423b6a4e81"),
    "client" : "1"
    "type" : "type1",
    "hierarchy" : "hier2",
    "creationDate" : ISODate("2015-09-10T13:06:44Z"),
    "model" : "m3"
}

我尝试使用给定的流/管道创建查询-

  1. Match client = 1 所在的文档($match 内部聚合)。
  2. group 通过“列表”和“层次结构”($group 内部聚合)。
  3. 我想通过最新的creationDate 字段聚合上一步中的文档组。而不是应用聚合函数($sum, $avg etc),我实际上想要每个组中具有最新creationDate 字段的文档

但我被困在流程的第 3 点。我不知道如何聚合具有相同 typehierarchy 的文档,并在单个 mongo 查询中为每种类型和层次结构选择具有最新日期 (creationDate) 的文档。

【问题讨论】:

    标签: mongodb aggregation-framework


    【解决方案1】:

    利用$group 阶段内的$first 运算符。如果有必要,然后包括一个$project 阶段。使用$$ROOT 变量将整个字段保存在名为record 的变量下。

    示例代码:

    db.t.aggregate([
    {$match:{"client":"1"}},
    {$sort:{"creationDate":-1}},
    {$group:{"_id":{"type":"$type",
                    "hierarchy":"$hierarchy"},
              "record":{$first:"$$ROOT"}}}
    ])
    

    添加如下$project阶段,获取顶层的文档字段,不需要,在客户端可以轻松处理。

    {$project:{"_id":0,"client":"$record.client","model":"$record.model",..}}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-07
      • 2013-11-25
      • 1970-01-01
      • 2019-10-31
      • 2023-03-14
      • 2013-12-27
      • 2020-09-09
      相关资源
      最近更新 更多