Mongoid order by length of array

2019-09-12 06:19发布

问题:

How to sort the Mongoid model by the length of the array which is a field inside the model.

回答1:

Document says that you can't orderby using size.

Try adding a new column containing the value of size and sort it which will work as order by.



回答2:

Mongo documentation says:

You cannot use $size to find a range of sizes (for example: arrays with more than 1 element). If you need to query for a range, create an extra size field that you increment when you add elements. Indexes cannot be used for the $size portion of a query, although if other query expressions are included indexes may be used to search for matches on that portion of the query expression.

So we cannot order by using mongo's $size.

You can solve your task by adding new field, which will store array size.

class Post
  include Mongoid::Document
  field :likes, type: Array, default: []
  field :likes_size, type: Integer

  before_save do
    self.likes_size = likes.size
  end
end

Sort posts by likes_size:

Post.order_by(likes_size: :desc)


回答3:

In ruby, you can sort an array like this :

my_array.sort_by(&:my_attr)

It will sort the array my_array by the attribute my_attr of each element inside the array.

You can also write it like this :

my_array.sort_by{|element| element.my_attr }

Which is exactly the same, it will sort by the my_attr attribute of each element. This second syntax is for when you want a more complex sort condition than just the result of a method of each element.

Documentation : http://ruby-doc.org/core-2.3.1/Enumerable.html#method-i-sort_by