MongoDb doesn't currently have the equivalent to the GREATEST
function. You could use a MapReduce, but it won't provide efficient immediate results. Additionally, you wouldn't effectively be able to return the other fields of the document. You'd need to do more than one query, or potentially duplicate all of the data. And, without running an update process for the results, it wouldn't be up to date as documents were modified, as a Map Reduce in MongoDb must be initiated manually.
The MongoDb aggregation framework wasn't intended for this pattern, and if it is possible, would result in a very lengthy pipeline. Also, it's currently limited to 16MB of results and doesn't easily return more than the fields you've aggregated. Returning select *
requires a manual field projection, potentially more than once depending on the desired output.
Given that you want to return multiple fields, and the result isn't an aggregation, I'd suggest doing something far simpler:
Precompute the result of a call to the greatest
function and store it in the document as a new field for easy access in a variety of queries.