[英]SQL to Mongodb using Rails + Mongoid
I have the following document structure in Mongoid: 我在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
I need to select all existing categories of posts to search. 我需要选择所有现有的帖子类别进行搜索。 If this were SQL, I would:
如果这是SQL,我将:
SELECT distinct category_name, category_id FROM posts
How would I do this in SQL query in Mongoid? 如何在Mongoid中的SQL查询中执行此操作?
If you want the model to return only the category_name and category_id fields, use "only". 如果您希望模型仅返回category_name和category_id字段,请使用“ only”。
Post.all.only(:category_name, :category_id)
would return all posts of the db but only the values of those 2 attributes, all the other attributes would be nil. Post.all.only(:category_name, :category_id)
将返回数据库的所有帖子,但仅返回这两个属性的值,所有其他属性均为nil。
But on Mongoid 3.1 you can do Post.distinct(:category_name)
and it would return a list of the different category names of the posts as an array. 但是在Mongoid 3.1上,您可以执行
Post.distinct(:category_name)
,它将以数组形式返回帖子的不同类别名称的列表。 On older versions of mongoid you can do Post.all.distinct(:category_name)
to obtain the same return. 在较早版本的Mongoid上,您可以执行
Post.all.distinct(:category_name)
获得相同的返回值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.