Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the object with the max value of a field [Mongoid]

is there anyway to return the object and not the value from Method:

Mongoid::Contexts::Enumerable#max

Link to the rdoc

An easy example is if you have collection of Users and they all have field :age => can i get the users that are oldest with max or should i use something else

like image 573
Todor Grudev Avatar asked Mar 30 '12 06:03

Todor Grudev


1 Answers

one_of_oldest_users = User.desc(:age).limit(1).first

That'll get you a one of users with the greatest age (in case there are several). If you want to get them all, the easiest way is to use a two-pass.

max_age = User.max(:age)
oldest_users = User.where(age: max_age)

# or, if you like one-liners
oldest_users = User.where(age: User.max(:age))

To make these queries efficient, you'll need an index on :age, of course.

like image 101
Sergio Tulentsev Avatar answered Nov 15 '22 00:11

Sergio Tulentsev