2016-04-14 47 views
0

我是mongodb和mongoid的新手。我习惯于Rails的Ruby ActiveRecord/mysql,所以请原谅我的无知。使用mongoid中的条件选择多个文档

在ActiveRecord的世界,如果我要搜索符合特定标准 (学生从一个特定的邮政编码)的所有记录,我可以用

students = Student.where(zipcode: "12345") 

,这将返回学生的数组。

使用Mongoid,如果我查询

Student.all.where(zipcode: "12345") 

它只是返回一个标准,我必须使用迭代器像

students = [] 
Student.all.where(zipcode: "12345").each { |s| students << s } 

有没有更好的方式做一个Mongoid /蒙戈查询获取所有文件 满足搜索条件,而无需使用ruby迭代器(.each)?

我已经从 https://docs.mongodb.org/ecosystem/tutorial/mongoid-queries/

指mongoid文件,找不到这个例子中的所有文件在一个查询。

回答

0

你被控制台上当,如果你认为:

students = Student.where(zipcode: "12345") 

给你的Student S IN students数组。这实际上给你一个students中的关系对象,但关系的inspect(由控制台调用)将从后面的数据库加载记录;同样,只要你试图用关系做任何事情,它会从数据库加载记录。

Mongoid的where表现相同,但它不需要解决在ActiveRecord关系所有相同的情况下建模实例。

做(既ActiveRecord的和Mongoid)最简单的事情就是打电话给to_a的关系/标准,如果你真的想要一个数组:

# ActiveRecord 
students = Student.where(zipcode: "12345")  # students is a relation 
students = Student.where(zipcode: "12345").all # students is still a relation 
students = Student.where(zipcode: "12345").to_a # students is now a real array 

# Mongoid 
students = Student.where(zipcode: "12345")  # students is a criteria 
students = Student.where(zipcode: "12345").all # students is still a criteria 
students = Student.where(zipcode: "12345").to_a # students is now a real array 

在这两种情况下,如果你想要一个数组,然后只是用to_a这么说。

+0

非常感谢解释 - 现在有道理。也只是了解到Student.where(...)返回一个条件,并且不会执行查询,直到它被分配给一个变量或迭代结束。 – Kannan