新手问题 关于 Mongoid 的问题

easonlovewan · 2016年04月20日 · 最后由 karloku 回复于 2016年04月20日 · 2392 次阅读

最近没事儿想玩玩儿 Mongoid,可是有个问题不太理解 我用 where 查询的时候

[99] pry(main)> User.where(name: "王哲")
=> #<Mongoid::Criteria
  selector: {"name"=>"王哲"}
  options:  {}
  class:    User
  embedded: false>

[100] pry(main)>

这个是没有查到吗?如果没有检索到为什么不反回 nil 呢? 紧接着我用 find 查到了

[103] pry(main)> User.find("522a9670098e71139a000001")
=> #<User _id: 522a9670098e71139a000001, created_at: nil, updated_at: 2016-01-16 01:15:33 UTC, email: "[email protected]", encrypted_password: "$2a$10$3Sb0D1WPGgkcp9UShoFv5e3kWKdccYikMa6VC9NoOqGrXyI5YdsxO", authentication_token: "BBdjB3yTMrszA2cUe51W", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 4587, current_sign_in_at: 2016-01-16 01:15:33 UTC, last_sign_in_at: 2016-01-13 01:05:11 UTC, current_sign_in_ip: "127.0.0.1", last_sign_in_ip: "127.0.0.1", name: "王哲", name_pinyin: "wangzhe", phone_num: "13810190339", phone_num2: "", remark: "", weixin_num: "", roles: ["1"], title: "", state: 0.0, seat_phone_no: "", storehouse_id: nil, city_id: "5307033e098e719c45000043", service_type_ids: nil, auto_ids: ["5242bcab098e716371000036"], battery_level: 27.00000190734863, location: [116.24116, 40.197981], role: "engineer", update_datetime: 2015-05-06 01:37:15 UTC>
[104] pry(main)>

我想问的是如果用 find 检索不到的话,就会反回 nil,可是 where 为什么反回一个 Mongoid 对象呢? 补充: 如果这边儿用 where 检索(不存在的列)为什么不报错?难道是 Mongoid 对 find 和 where 有不同的处理?

[105] pry(main)> User.where(ifsdafdsd: "522a9670098e71139a000001")
=> #<Mongoid::Criteria
  selector: {"ifsdafdsd"=>"522a9670098e71139a000001"}
  options:  {}
  class:    User
  embedded: false>

[106] pry(main)>

延迟执行,访问内容的时候才执行,例如加个 .to_a

where 返回的是一个查询条件的集合,它并没有去做查询,还有 Mongoid 是 nosql, 并没有列的说法

后一个问题,mongodb 没有列,每个文档都有自己的模式,所以查不存在的字段是有效的。

#3 楼 @rei 受益了,还是对 mongodb 不太了解,恶补吧

#3 楼 @rei #2 楼 @shinkxw 那我可不可以这样理解,我做检索的时候不能用 where,要用 find 吗?

@rei 如果 where 不执行查询的话?那我怎么通过 find 对其它属性进行查询呢?

#6 楼 @easonlovewan where 查询结果是个集合,遍历集合元素的时候就会执行。

你想要做什么?

#7 楼 @rei where 查询结果是个集合,遍历集合元素的时候就会执行。明白了

感觉类似 ActiveRecord::Relation

#9 楼 @pathbox 是的 where 的最终结果应该就是 MongoId::Relation

ActiveRecord.where 返回的也是一个 lazy 的查询集,只不过在控制台里显示的时候会被实际执行一下 (同 pp).

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