MongoDB 最大值查询和_id

MongoDB max values query and _id

db.collections.find()

    { "_id" : ObjectId("55b0c2a0339bf8d00ab0bade"), "score" : 46, "playerid" : "45"}
    { "_id" : ObjectId("55b0c2de339bf8d00ab0badf"), "score" : 88, "playerid" : "45"}
    { "_id" : ObjectId("55b0cbca17f398f4281ab931"), "score" : 46, "playerid" : "99"}
    { "_id" : ObjectId("55b15ababe2df0f430d1cb93"), "score" : 89, "playerid" : "45"}

我想做的是检索得分最高的所有文档。如果同一个玩家出现不止一次,那么我们将获得该特定玩家得分最高的文档。

结果如下所示:

    { "_id" : "55b0cbca17f398f4281ab931", "score" : 46 }
    { "_id" : "55b15ababe2df0f430d1cb93", "score" : 89 }

这就是我卡住的地方:

db.players.aggregate([

{ "$group": { 
    "_id": "$playerid",
    score: { $max: "$score" }
} }
])

哪个returns:

    { "_id" : "99", "score" : "46" }
    { "_id" : "45", "score" : "89" }

现在,这是正确的。但我只需要 ObjectID。

而不是 $max then use $sort and $first,其他属性对您很重要:

db.players.aggregate([
   { "$sort": { "score": -1 } },
   { "$group": { 
       "_id": "$playerid",
       "docId": { "$first": "$_id" },
       "score": { "$first": "$score" }
   }}
])

$max 运算符当然只适用于您指定的 "one" 字段。为了从集合文档中获取详细信息,您需要 $sort 并在分组边界上获取 $first 事件。

当然$first是相对于$sort的顺序是"descending",否则使用$last升序,对于"maximum"的值排序键。