The problem with Mongoid ordering

I use mongoid to store data. I have a scenario where I have to sort my parents by the number of dependents they have. My model is simple:

References to the parent model dependent names stored_as => array
Dependent model reference_many parentsstored_as => array

I do not want to go through my parents, find the number of dependents, store them in an array and upload them to my view.

I need to sort parents by the number of dependents with only one query. Is it possible?

Thank.

+3
source share
1 answer

. - :

class MyModel
  include Mongoid::Document

  references_many :things
  field :thing_count, :type => Integer

  before_update :set_thing_count
  def set_thing_count
    self.thing_count = self.things.count
  end
end

:

MyModel.asc(:thing_count)

Mongoid , , , . , !

+8

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


All Articles