正如前面所有评论所指出的,这可以使用聚合框架来实现。我将 C# 留给你,但我将演示一个使用 Mongo shell 的简单示例。
从以下示例数据开始。
> db.runners.find()
{ "_id" : ObjectId("50b3ec3c9dc68d628bd11869"), "name" : "a", "d" : ISODate("2012-10-29T00:00:00Z"), "time" : 10.3 }
{ "_id" : ObjectId("50b3ec429dc68d628bd1186a"), "name" : "a", "d" : ISODate("2012-10-20T00:00:00Z"), "time" : 12.3 }
{ "_id" : ObjectId("50b3ec549dc68d628bd1186b"), "name" : "b", "d" : ISODate("2012-10-29T00:00:00Z"), "time" : 11.45 }
{ "_id" : ObjectId("50b3ec5a9dc68d628bd1186c"), "name" : "b", "d" : ISODate("2012-10-25T00:00:00Z"), "time" : 11 }
{ "_id" : ObjectId("50b3ec6a9dc68d628bd1186d"), "name" : "c", "d" : ISODate("2012-10-25T00:00:00Z"), "time" : 10.8 }
{ "_id" : ObjectId("50b3f1249dc68d628bd1186e"), "name" : "b", "d" : ISODate("2012-11-13T00:00:00Z"), "time" : 23.2 }
然后,以下聚合查询返回:
> db.runners.aggregate({$sort:{name:1,d:-1}},{$group:{_id:"$name",d:{$first:"$d"},time:{$first:"$time"}}})
{
"result" : [
{
"_id" : "c",
"d" : ISODate("2012-10-25T00:00:00Z"),
"time" : 10.8
},
{
"_id" : "b",
"d" : ISODate("2012-11-13T00:00:00Z"),
"time" : 23.2
},
{
"_id" : "a",
"d" : ISODate("2012-10-29T00:00:00Z"),
"time" : 10.3
}
],
"ok" : 1
}
首先,$sort
操作员按runners
降序排序name
,d
因此每个跑步者姓名的第一个文档应该是每个跑步者最近的跑步日期。然后,$group
操作员为每个跑步者提取第一个文档,以及该比赛的最近跑步日期和运行时间。