2016-04-14 48 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