Mongoid order by length of array

2019-09-12 06:42发布

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

3条回答
疯言疯语
2楼-- · 2019-09-12 07:06

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

查看更多
做自己的国王
3楼-- · 2019-09-12 07:07

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)
查看更多
ら.Afraid
4楼-- · 2019-09-12 07:08

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.

查看更多
登录 后发表回答