在 Mongoid 中,条件代表查询,而不是元素。
您可以将条件视为过滤器、范围、查询对象。
一旦你有了一个条件(范围),你就可以获取元素,对数据库执行一个实际的查询,使用一个应该迭代元素或返回一个元素的方法,例如:.first,@ 987654322@、.to_a、.each、.map等
这样效率更高,允许您从其他简单的“查询”中组合出复杂的“查询”。
例如,您可以在类中创建一些命名范围:
class User
include Mongoid::Document
field :name, type: String
field :age, type: Integer
field :admin, type: Boolean
scope :admins, where(admin: true) # filter users that are admins
scope :with_name, (name)-> { where(name: name) } # filter users with that name
end
然后你可以创建一些标准对象:
admins = User.admins
johns = User.with_name('John')
admin_johns = User.admins.with_name('John') # composition of criterias, is like doing ANDs
young = User.where(:age.lt => 25) # the Mongoid method .where also returns a criteria
到目前为止,您没有向 mongo 数据库触发任何查询,您只是在编写查询。
您可以随时保持链接条件,以进一步细化查询:
young_admins = admins.merge(young)
old_admins = admins.where(age.gt => 60)
最后,获取包含元素的数组:
# Execute the query and an array from the criteria
User.all.to_a
User.admins.to_a
admins.to_a
young_admins.to_a
# Execute the query but only return one element
User.first
admins.first
johns.last
# Execute the query and iterate over the returned elements
User.each{|user| ... }
User.admins.each{|admin_user| ... }
johns.map{|john_user| ... }
因此,在 Class 中定义一些命名范围,然后使用它们创建条件,并在需要时进行真正的查询(延迟加载)。即使您不知道自己需要标准,标准也会为您处理所有这些。