【问题标题】:How to get lastest record each group in mongodb?如何获取mongodb中每个组的最新记录?
【发布时间】:2020-07-29 14:13:55
【问题描述】:

我有一个列表消息,格式如下:

 [
   {
     "_id": 1,
     "groupID": 1,
     "content": "content 1",
     "createAt": 1
   },
 
   {
     "_id": 2,
     "groupID": 1,
     "content": "content 2",
     "createAt": 2
   },
   {
     "_id": 3,
     "groupID": 2,
     "content": "content 3",
     "createAt": 3
   },
   {
     "_id": 4,
     "groupID": 2,
     "content": "content 4",
     "createAt": 4
   },
   {
     "_id": 5,
     "groupID": 2,
     "content": "content 5",
     "createAt": 5
   },
   {
     "_id": 6,
     "groupID": 2,
     "content": "content 6",
     "createAt": 6
   }
 ]

如何获取每个组的最后一条消息(与“createAt”比较)?

预期结果:

{
   "_id": 2,
   "groupID": 1,
   "content": "content 2",
   "createAt": 2
}

{
   "_id": 6,
   "groupID": 2,
   "content": "content 6",
   "createAt": 6
}

【问题讨论】:

    标签: mongodb mongoose mongodb-query aggregation-framework


    【解决方案1】:

    您可以$sort + $group 并使用$$ROOT 完全保留最后一个文档。然后你需要$replaceRoot 将最后一个文档提升到根级别:

    db.collection.aggregate([
        { $sort: { createAt: 1 } },
        {
            $group: {
                _id: "$groupID",
                last: { $last: "$$ROOT" }
            }
        },
        {
            $replaceRoot: { newRoot: "$last" }
        }
    ])
    

    Mongo Playground

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-10-30
      • 2017-02-05
      • 2018-11-22
      • 1970-01-01
      • 2016-11-26
      • 1970-01-01
      相关资源
      最近更新 更多