且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用Mongoid/mongodb提取,建模和更改数据模型

更新时间:2023-01-09 10:41:19

您要做两件事:

  • 使用db查询过滤用户,而不是在应用程序中过滤
  • 仅从数据库中获取您需要的字段,而不是整个用户对象(假设用户中还有其他内容,为简便起见,在此省略)

  • Filter the users with db query instead of filtering in application
  • only fetch fields you need from db, rather than the whole user objects(assuming you have some other stuff in user, which you omitted here for brevity)

Competitor = Struct.new(:html_url, :description, :user)
competitors = []
User.where('watchlists.tags_array' => %w[ruby web framework]).
    only(:nickname, :watchlists).each do |u|
  u.watchlists.where(:tags_array => %w[ruby web framework]).each do |wl|
    competitors << Competitor.new(wl.html_url, wl.description, u.nickname)
  end
end

PS:可能您不想在User.all上使用map,如果您有大量用户文档,它将需要大量内存.另外,您不是在使用映射的用户,而是自己在competitors数组中收集结果,因此each应该可以正常工作.

PS: Probably you do not want to use map on User.all, it will require a lot of memory if you have lots of heavy user documents. Also, you are not using the mapped users, but instead collecting results in the competitors array yourself, so each should work just fine.