使用Mongo聚合查询按类型获取最新文档

时间:2018-01-16 04:30:53

标签: mongodb mongodb-query aggregation-framework

我有一个mongo集合,我想从中获取一些特定的数据。我需要每种类型的最新文档。数据如下所示:

{"id":"100", "type":"A", "date":"2018-01-15T22:19:07.017", "firstName":"Jack", "lastName":"Miller", "age":34}
{"id":"101", "type":"B", "date":"2017-12-04T23:28:49.889", "firstName":"Bob", "lastName":"Jackson", "age":43}
{"id":"102", "type":"B", "date":"2017-12-11T22:06:33.150", "firstName":"Karen", "lastName":"Decker", "age":12}
{"id":"103", "type":"A", "date":"2017-12-18T21:27:31.847", "firstName":"Sally", "lastName":"Rich", "age":19}
{"id":"104", "type":"A", "date":"2017-12-19T23:07:01.292", "firstName":"Joe", "lastName":"Hunk", "age":11}
{"id":"105", "type":"C", "date":"2018-01-08T21:25:25.715", "firstName":"Tallia", "lastName":"Hope", "age":86}

所以每种类型的最新版本都是这样的:

{"id":"100", "type":"A", "date":"2018-01-15T22:19:07.017", "firstName":"Jack", "lastName":"Miller", "age":34}
{"id":"102", "type":"B", "date":"2017-12-11T22:06:33.150", "firstName":"Karen", "lastName":"Decker", "age":12}
{"id":"105", "type":"C", "date":"2018-01-08T21:25:25.715", "firstName":"Tallia", "lastName":"Hope", "age":86}

我认为这里找到的聚合操作(https://docs.mongodb.com/manual/aggregation/)是可行的方法。我尝试使用$ group累加器对类型进行分组,然后获得$ max日期,但是我不知道如何获取文档的其余部分。我可以通过多个查询轻松完成此操作,但如果可能的话,我想使用一个查询。

聚合操作是否是正确的选择?也许我在这里错过了一些简单的东西。

1 个答案:

答案 0 :(得分:1)

您可以尝试此解决方案:

db.test.aggregate([
    { $sort: { "date": -1 } },
    { $group: { _id: "$type", latest: { $first: "$$ROOT" } }},
    { $project : {_id : 0, id : "$latest.id", type : "$latest.type", date : "$latest.date", firstName : "$latest.firstName", lastName : "$latest.lastName", }},
    { $sort: { "type": 1 } }
])

如果您提供此输入:

{"id":"100", "type":"A", "date":"2018-01-15T22:19:07.017", "firstName":"Jack", "lastName":"Miller", "age":34}
{"id":"101", "type":"B", "date":"2017-12-04T23:28:49.889", "firstName":"Bob", "lastName":"Jackson", "age":43}
{"id":"102", "type":"B", "date":"2017-12-11T22:06:33.150", "firstName":"Karen", "lastName":"Decker", "age":12}
{"id":"103", "type":"A", "date":"2017-12-18T21:27:31.847", "firstName":"Sally", "lastName":"Rich", "age":19}
{"id":"104", "type":"A", "date":"2017-12-19T23:07:01.292", "firstName":"Joe", "lastName":"Hunk", "age":11}
{"id":"105", "type":"C", "date":"2018-01-08T21:25:25.715", "firstName":"Tallia", "lastName":"Hope", "age":86}

这是查询生成的所需输出:

{ "id" : "100", "type" : "A", "date" : "2018-01-15T22:19:07.017", "firstName" : "Jack", "lastName" : "Miller" }
{ "id" : "102", "type" : "B", "date" : "2017-12-11T22:06:33.150", "firstName" : "Karen", "lastName" : "Decker" }
{ "id" : "105", "type" : "C", "date" : "2018-01-08T21:25:25.715", "firstName" : "Tallia", "lastName" : "Hope" }