Reputation: 1513
is there anyway to return the object and not the value from Method:
Mongoid::Contexts::Enumerable#max
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
Upvotes: 6
Views: 3978
Reputation: 230521
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.
Upvotes: 14