Mongo finders and criteria

倖福魔咒の 提交于 2019-12-06 08:35:57

You can treat the criteria object as array. Finders return a criteria object because criteria is chainable in mongoid. That is, you can do something like:

users = User.where(:activated => true)
users = users.where(:created_at.gte => Time.now - 1.week) unless params[:recent].blank?
users = users.where(:gender => params[:gender].downcase) if %w[m f].include?(params[:gender].downcase

Anytime you use any methods which are not defined in Criteria, mongoid will actually run the query and fetch the results and treat them as array. If you specifically want the results to be returned as array, you can always call User.all.to_a. But keep in mind that following two are mostly equivalent:

User.all.each {|u| puts u.id}
User.all.to_a.each {|u| puts u.id}

But there is one issue with the later, it will fetch all the documents in memory once and can lead to too much of memory consumption. However, first one uses Mongodb cursors to fullest and only loads documents yielded by cursor, means controlled memory usage.

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