How do you get a specific Document from an array of documents, where a value inside that document is the highest in all of the documents in the array?
For example:
{
_id: "notImportant",
array: [
{
name: "Peter",
age: 17
},
{
name: "Carl",
age: 21
},
{
name: "Ben",
age: 15
}
]
}
How would I get the document where age is the max out of all the documents in the array, in this case
{
name: "Carl",
age: 21
}
I tried using $max in a projection after an $unwind, but that only gives me the age: 21 bit and not what else is in the documents (in the example: name). I also tried matching after an unwind+projection like so:
{
"age": {"$eq": {"$max": "$age"}}
}
But that gives me an empty return. It is also empty when I use $lt or $gt.
Edit:
I have seen the answers that suggest to use a sort and then limit to 1, but really that seems very inefficient. My array has thousands of datapoints, fetching the one document from it with the specified field being the maxium of all the values would require going through the list once, however sorting it would require n*log(n) operations just to fetch the very top of the list. Surely there is a way to do this more efficiently.