Mongoid 按数组长度排序

Mongoid order by length of array

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

在 ruby 中,您可以像这样对数组进行排序:

my_array.sort_by(&:my_attr)

它将根据数组中每个元素的属性 my_attr 对数组 my_array 进行排序。

你也可以这样写:

my_array.sort_by{|element| element.my_attr }

也完全一样,会按照每个元素的my_attr属性进行排序。这第二种语法适用于当您需要更复杂的排序条件而不仅仅是每个元素的方法的结果时。

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

Mongo 文档 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.

所以我们无法使用mongo的$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

likes_size 排序 posts:

Post.order_by(likes_size: :desc)

文档说您不能使用尺寸来排序。

尝试添加一个包含大小值的新列并对其进行排序,这将作为排序依据。