【问题标题】:Mongo aggregation to filter documents based on the max of a fieldMongo聚合根据字段的最大值过滤文档
【发布时间】:2021-04-06 15:58:02
【问题描述】:

该集合具有键、版本、日期和状态等字段。同一个键在集合中可以有多个条目,具有唯一的版本、日期和状态。

我们如何编写一个聚合来查找所有具有最大版本的文档。 例如 - 我在这里创建了一个示例集合 - https://mongoplayground.net/p/nyAdYmzf59H

预期的输出是

[{
        "key": 1,
        "version": 2,
        "date": "Feb/10",
        "status": "DRAFT"
    }, {
        "key": 2,
        "version": 1,
        "date": "March/10",
        "status": "ACTIVE"
    }, {
        "key": 3,
        "version": 3,
        "date": "Jun/10",
        "status": "DRAFT"
    }
]

【问题讨论】:

    标签: mongodb mongodb-query aggregation-framework


    【解决方案1】:

    演示 - https://mongoplayground.net/p/WyKH2fVbWfA

    db.collection.aggregate([
      { "$sort": { "version": -1 } }, // sort descending by version 
      {
        "$group": {
          "_id": "$key", // group by key
          "version": { "$first": "$version" }, // pick top version which will be max here
          "date": { "$first": "$date" },
          "status": { "$first": "$status"}
        }
      },
      { $project: { _id: 0,  key: "$_id", version: 1, date: 1, status: 1 }}
    ])
    

    演示 - https://mongoplayground.net/p/e1Bw7rVGd0Q

    db.collection.aggregate([
      { $sort: { "version": -1 } },
      { $group: { "_id": "$key", "doc": { "$first": "$$ROOT" } } },
      { $replaceRoot: { "newRoot": "$doc" } },
      { $project: { _id: 0 } }
    ])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-03
      • 2019-07-03
      • 2019-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-26
      相关资源
      最近更新 更多