[英]MongoDB max values query and _id
db.collections.find() 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"}
What I'm trying to do, is retrieve all documents with the largest score. 我正在尝试做的是检索所有得分最高的文档。 If the same player occurs more than once, then we get the document with the largest score for that particular player.
如果同一个玩家出现不止一次,那么我们会获得该特定玩家得分最高的文档。
The result would look like this: 结果如下所示:
{ "_id" : "55b0cbca17f398f4281ab931", "score" : 46 }
{ "_id" : "55b15ababe2df0f430d1cb93", "score" : 89 }
This is where I'm stuck: 这就是我被困的地方:
db.players.aggregate([
{ "$group": {
"_id": "$playerid",
score: { $max: "$score" }
} }
])
which returns: 返回:
{ "_id" : "99", "score" : "46" }
{ "_id" : "45", "score" : "89" }
Now, this is correct. 现在,这是正确的。 But I just need the ObjectID instead.
但我只需要ObjectID。
Instead of $max
then use $sort
and $first
where the other properties are important to you: 而不是
$max
然后使用$sort
和$first
,其他属性对您很重要:
db.players.aggregate([
{ "$sort": { "score": -1 } },
{ "$group": {
"_id": "$playerid",
"docId": { "$first": "$_id" },
"score": { "$first": "$score" }
}}
])
The $max
operator of course only works on "one" field that you specify. $max
运算符当然只适用于您指定的“one”字段。 In order to get detail from the collection document then you need to $sort
and get the $first
occurance on the grouping boundary. 为了从集合文档中获取详细信息,您需要
$sort
并在分组边界上获得$first
。
Of course $first
is relative to the $sort
order which is "descending", otherwise use $last
with ascending order, for the "maximum" value on the sort key. 当然
$first
相对于$sort
命令是“降序”,否则使用$last
和升序,作为排序键的“最大”值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.