Get all documents with maximum value using aggregation in mongodb

I want to get "all documents" that have the highest value for a particular field and then grouped by another field.

Consider the data below:

_id:1, country:india,  quantity:12,  name:xyz
_id:2, country:USA,    quantity:5,   name:abc
_id:3, country:USA,    quantity:6,   name:xyz
_id:4, country:india,  quantity:8,   name:def
_id:5, country:USA,    quantity:10,  name:jkl
_id:6, country:india,  quantity:12,  name:jkl

The answer should be

country:india max-quantity:12
name xyz
name jkl 

country:USA max-quantity:10
name jkl

I tried several queries, but I can only get the maximum value without a name, or I can group, but it shows all the values.

db.coll.aggregate([{
    $group:{
        _id:"$country",
        "maxQuantity":{$max:"$quantity"}
    }
}])

for example, the above will give the maximum quantity for each country, but how to combine with another field so that it displays all documents of the maximum quantity.

+5
source share
2 answers

, $push . , , $max, , :

db.coll.aggregate([
    { "$group":{ 
        "_id": "$country",
        "maxQuantity": { "$max": "$quantity" },
        "docs": { "$push": {
            "_id": "$_id",
            "name": "$name",
            "quantity": "$quantity"
        }}
    }},
    { "$project": {
        "maxQuantity": 1,
        "docs": {
            "$setDifference": [
               { "$map": {
                   "input": "$docs",
                   "as": "doc",
                   "in": {
                       "$cond": [ 
                           { "$eq": [ "$maxQuantity", "$$doc.quantity" ] },
                           "$$doc",
                           false
                       ]
                   }
               }},
               [false]
            ]
        }
    }}
])

, , , , , , , .

_id , "" $setDifference. . , , "" , .

$map, , .

, BSON 16 , , , ( ), , "max", - .

+12

, , :

[
{"$match":{"name":{"$in":["USA","india"]}}}, // stage one
{ "$sort": { "quanity": -1 }}, // stage three
{"$limit":2 } // stage four - count equal ["USA","india"] length
]

, , :

[
{"$project": {
    "country": "$country",
    "quantity": "$quantity",
    "document": "$$ROOT" // save all fields for future usage

}},
{ "$sort": { "quantity": -1 }},
{"$group":{"_id":{"country":"$country"},"original_doc":{"$first":"$document"} }}
]
+3

Source: https://habr.com/ru/post/1613300/


All Articles