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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With