2013-03-22 45 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)以获得相同的回报。