javascript – MongoDB最大值查询和_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" }
} }
])

返回:

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

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

最佳答案 而不是
$max然后使用
$sort
$first,其他属性对您很重要:

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

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

当然$first相对于$sort命令是“降序”,否则使用$last升序,作为排序键的“最大”值.

点赞