MongoDB Mongoid: find 和 where 有哪些区别?

bryanwong · 2012年02月12日 · 最后由 liwen_zhang 回复于 2012年04月19日 · 5181 次阅读
1.9.3p0 :058 > Post.where(:id => '4f35120b1d41c819ad000002')
 => #<Mongoid::Criteria
  selector: {:id=>"4f35120b1d41c819ad000002,"},
  options:  {},
  class:    Post,
  embedded: false>

1.9.3p0 :103 > Post.find('4f35120b1d41c819ad000002')
 => #<Post_id: 4f35120b1d41c819ad000002, _type: nil, created_at: 2012-02-10 12:48:11 UTC, updated_at: 2012-02-10 12:48:11 UTC, content: "11111111111", commented_at: nil, comments_count: 0, views_count: 5, user_id: BSON::ObjectId('4f3511e61d41c819ad000001')> 
  1. find 和 where 的差别,是不是 find 只能接受 BSON::ObjectId 做参数?而 where 却可以接受 :conditions 参数?

  2. Post.where 返回的 Mongoid::Criteria 是什么类型?是一个数组吗?

谢谢!

  1. 应该是这样的,不过 find 还可以接受 id 数组,而且 find 找不到记录会抛错,where 不会

  2. 引用 Mongoid 的官网描述:

    All queries in Mongoid are Criteria, which is a chainable and lazily evaluated wrapper to a MongoDB dynamic query. Criteria only touch the database when they need to, for example on iteration of the results, and when executed wrap a cursor in order to keep memory management and performance predictable.
    

Criteria 是一个中间对象,保持按需查询以提高效率。

find 找不到会报错 where 找不到会返回空记录

where 是延时查询

where 返回的是 ActiveRecord::Relation,也就是 4 楼说的延时查询

@liwen_zhang 什么是延时查询,可以讲解一下吗?

@jacksv123 Relation 或者 Scope 的对象保存了我们希望进行的查询条件信息,但是数据库并没有实际执行这个查询操作。即除非真正使用这些数据,否则实际的查询就不进行,实际的数据库查询不会在 controller 调用的时候执行。而是,在 view 页面进行迭代输出的时候执行。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号