Mongo发现者和条件 [英] Mongo finders and criteria

查看:76
本文介绍了Mongo发现者和条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Mongoid映射器的rails应用程序中使用MongoDB.但是我不理解查询的finderscriteria.例如,在Finders部分的蒙古式文档中,查询为Model.all,但是如果我使用该查询(例如User.all),则控制台返回条件而不是结果:

I use MongoDB in my rails application with Mongoid mapper. But I don't understand finders and criteria of querying. For example in mongoid documentaion in section Finders is query Model.all, but if I use that(for example User.all), console return criteria and not the result:

 => #<Mongoid::Criteria
  selector: {},
  options:  {},
  class:    User,
  embedded: false>

但是,如果我使用查找器Model.firstModel.last,则控制台会返回特定结果. (User.first返回特定用户,其字段为:email:username等).为什么Model.all在文档中写为finders?而如果需要全部Users或例如Posts,我该怎么办?

But if I use finder Model.first or Model.last, console return specific result. (User.first return specific user, with its fields, as :email, :username and other). Why Model.all wrote in documentation as finders? And what I need doing if I need get all Users or for example Posts?

推荐答案

您可以将条件对象视为数组.查找器返回条件对象,因为条件可以在蒙古语中链接.也就是说,您可以执行以下操作:

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

无论何时使用Criteria中未定义的任何方法,mongoid都会实际运行查询并获取结果并将其视为数组.如果您特别希望将结果作为数组返回,则始终可以调用User.all.to_a.但是请记住,以下两个大部分是等效的:

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}

但是后面的一个问题是,它将一次提取内存中的所有文档,并且可能导致过多的内存消耗.但是,第一个使用Mongodb游标来达到最佳状态,并且仅加载游标产生的文档,这意味着可以控制内存使用.

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.

这篇关于Mongo发现者和条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆