Get the object with the maximum field value [Mongoid]

is there anyway to return an object, not a value from a method:

Mongoid::Contexts::Enumerable#max 

Link to rdoc

Easy example: if you have a collection of users and all of them have a field: age => can I get users who are the oldest with max or should I use something else.

+6
source share
1 answer
 one_of_oldest_users = User.desc(:age).limit(1).first 

This will give you one of the users with the greatest age (if there are several). If you want to get them all, the easiest way is to use two passes.

 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.

+10
source

Source: https://habr.com/ru/post/912023/


All Articles