将多个Mongoid标准的结果合并为一个标准

时间:2019-05-10 08:59:33

标签: ruby-on-rails ruby mongoid

我列出了人们进行对话的活动清单。我的目的是收集发生在此类事件中的所有对话。

我尝试查询每个事件并将其添加到数组中,然后尝试展平并删除重复项:

# this works fine
def event_conv_selector(event) 
  user_ids = event.participations.pluck(:user_id)
  users = ::User.in(id:user_ids)
  Conversation.where(:created_at => event.range_for_conversations).in(initiator_profile_id: students.pluck(:id))
end

conversations = []
# RAM can't hold that many conversations, it fails...
Event.each do |event|
  conversations << event_conv_selector(event).to_a
end

conversations.flatten.uniq(&:_id)

我的问题是:有没有一种方法可以查询和合并其他条件中所有条件的结果,而我可以处理这些条件而不会占用我的RAM?

非常感谢!

2 个答案:

答案 0 :(得分:0)

如果您只需要唯一的ID,则只需保留ID,而不要保留整个对象。

require 'set'

def event_conv_selector(event)
  Conversation...pluck(:id) # return id array
end

conversations = Set.new
Event.each do |event|
  conversations.merge(event_conv_selector(event))
end
conversations.to_a

否则,您可以覆盖Conversation类的eql?并仅将唯一对象保留在set集合中。

您不清楚我的查询和关系。但是,check this gem可以提高对Mongoid的渴望负荷,即使对于嵌套/多态关联也是如此。

答案 1 :(得分:0)

如果问题仅在于对话对象,则可以尝试:

# same as before
def event_conv_selector(event) 
  user_ids = event.participations.pluck(:user_id)
  users = ::User.in(id:user_ids)
  Conversation.where(:created_at => event.range_for_conversations).in(initiator_profile_id: students.pluck(:id))
end

conversation_ids = Set.new
Event.each do |event|
  conversation_ids += event_conv_selector(event).pluck(:id)
end