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操作符只能在你指定的“一个”字段上工作。 为了从集合文档中获得详细信息,您需要$sort并获取分组边界上的$first

当然, $first是相对于“降序”的$sort顺序,否则使用升序sorting的$last ,sorting键上的“最大”值。