mongoid--查询的注意事项

mongoid查询方法简介

mongoid是ruby版本的mongoldb-driver.

mongoid实现的查询方法和active record极其类似,所以对于rails用户来说是很友好的。

例如:

class Band
  include Mongoid::Document

  field :name
  field :founded
end

Band.where(name: "Depeche Mode")
Band.
  where(:founded.gte => "1980-1-1").
  in(name: [ "Tool", "Deftones" ]).
  union.
  in(name: [ "Melvins" ])

注意事项

正常的wehre和in等查询方式,返回的结果是类似ActiveRecord::Relation的Mongoid::Criteria对象,可以链式调用,无限连接。

而且Mongoid::Criteria对象和ActiveRecord::Relation类似,是懒执行的,也就是说除非调用了数组的方法,才会触发真正的查询,否则不会真的去连接mongodb和进行查询。

排序 sort

排序时使用sort方法,但是sort方法返回的对象是 Mongoid::Contextual::Mongo,这个对象是不支持再连接条件的。

所以,排序要放到查询的后面!

支持分页查询功能 page,per

分页功能和rails的插件kaminary以及will_paginate都很相似,用page和per分别表示第几页和每页多少条记录。

Band.where(name: "Depeche Mode").per(10).page(2).sort({ name: 1 })

page可以单独使用,但是per不可以。如果要用per,必须先加上page!

page和per的实质是用mongoldb的skip和limit实现的, 分别类似mysql的offset和limit

参考资料

https://docs.mongodb.org/ecosystem/tutorial/mongoid-queries/

你可能感兴趣的:(mongoid,mongodb)