rubymongodbmongodb-ruby

Getting the highest value of a column in MongoDB


I've been for some help on getting the highest value on a column for a mongo document. I can sort it and get the top/bottom, but I'm pretty sure there is a better way to do it.

I tried the following (and different combinations):

transactions.find("id" => x).max({"sellprice" => 0})

But it keeps throwing errors. What's a good way to do it besides sorting and getting the top/bottom?

Thank you!


Solution

  • max() does not work the way you would expect it to in SQL for Mongo. This is perhaps going to change in future versions but as of now, max,min are to be used with indexed keys primarily internally for sharding.

    see http://www.mongodb.org/display/DOCS/min+and+max+Query+Specifiers

    Unfortunately for now the only way to get the max value is to sort the collection desc on that value and take the first.

    transactions.find("id" => x).sort({"sellprice" => -1}).limit(1).first()