Mongoid order by length of array

a 夏天 提交于 2019-12-25 07:14:15

问题


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



来源:https://stackoverflow.com/questions/38350192/mongoid-order-by-length-of-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!