【问题标题】:SQL to Mongodb using Rails + Mongoid使用 Rails + Mongoid SQL 到 Mongodb
【发布时间】:2013-03-22 18:32:51
【问题描述】:

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

【问题讨论】:

    标签: ruby-on-rails mongodb mongoid nosql


    【解决方案1】:

    如果您希望模型仅返回 category_name 和 category_id 字段,请使用“only”。 Post.all.only(:category_name, :category_id) 将返回数据库的所有帖子,但仅返回这 2 个属性的值,所有其他属性将为 nil。

    但在 Mongoid 3.1 上,您可以使用 Post.distinct(:category_name),它会以数组的形式返回帖子的不同类别名称的列表。在旧版本的 mongoid 上,您可以通过 Post.all.distinct(:category_name) 获得相同的回报。

    【讨论】:

      猜你喜欢
      • 2013-04-10
      • 2021-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-03
      相关资源
      最近更新 更多