Ruby on rails 使用Rails+;蒙哥德

Ruby on rails 使用Rails+;蒙哥德,ruby-on-rails,mongodb,mongoid,nosql,Ruby On Rails,Mongodb,Mongoid,Nosql,我在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 distinc

我在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查询中如何执行此操作?

如果希望模型仅返回category\u name和category\u id字段,请使用“only”
Post.all.only(:category\u name,:category\u id)
将返回数据库的所有Post,但仅返回这两个属性的值,所有其他属性将为零

但在Mongoid 3.1上,您可以执行
Post.distinct(:category\u name)
,它将以数组形式返回帖子的不同类别名称列表。在旧版本的mongoid上,您可以执行
Post.all.distinct(:category\u name)
以获得相同的回报