2013-03-22 48 views
0

我在Mongoid下面的文檔結構:SQL到MongoDB的使用Rails + Mongoid

class Post 
    include Mongoid::Document 
    field "title", type: String 
    field "body", type: String 
    field "category_name", type: String 
    field "category_id", type: Integer 
end 

,我需要選擇職位的所有現有類別進行搜索。如果這是SQL,我會:

SELECT distinct category_name, category_id FROM posts 

我怎麼會在Mongoid的SQL查詢中做到這一點?

回答

0

如果您希望模型僅返回category_name和category_id字段,請使用「only」。 Post.all.only(:category_name, :category_id)會返回數據庫的所有文章,但只返回這兩個屬性的值,其他所有屬性都是零。

但在Mongoid 3.1上,你可以做Post.distinct(:category_name),它會以數組的形式返回不同類別名稱的列表。在較早版本的mongoid上,您可以執行Post.all.distinct(:category_name)以獲得相同的回報。