2

I have a rudimentary at best understanding of MongoDB and aggregation. I have not been able to find a clear example of how one might compare multiple documents which match a criteria and return 1 document with the maximum value in a specific attribute.

Say we have the following documents in a collection:

{ name: "a" , value: 2 }
{ name: "a" , value: 4 }
{ name: "a" , value: 6 }
{ name: "b" , value: 2 }
{ name: "b" , value: 8 }

How would I filter by name (eq("name","a")) and then return the document with the highest value?

Jonathan Woollett-light
  • 2,813
  • 5
  • 30
  • 58
  • Maybe there is an answer [here](https://stackoverflow.com/questions/32076382/mongodb-how-to-get-max-value-from-collections). ```db.collection.find({name: "a"}).sort({value:-1}).limit(1)``` – Bogdan Oros May 07 '19 at 20:44
  • @BogdanOros That's my current method of doing it, looking for something a little more elegant/efficient. Thank you anyway, should've mentioned. – Jonathan Woollett-light May 07 '19 at 20:49
  • You may use some aggregation features with ```$max```, but the sort+limit solution is more efficient. – Bogdan Oros May 07 '19 at 20:52
  • @JonathanWoollett-light in addition, to make the `sort().limit()` efficient, you would also need an index on the `value` field. – kevinadi May 08 '19 at 03:24

1 Answers1

0

try this

 db.collection.aggregate(
 [
   {
     $group: {
       _id: "$name",
       values: {$addToSet: "$value"}
     }
   },
   {
     $project:{
     _id: 0, name: "$_id", value: {$max: "$values"}
     }
   }
])