首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Mongoid查询

Mongoid查询
EN

Stack Overflow用户
提问于 2011-11-23 18:32:26
回答 1查看 516关注 0票数 1

我有一些RoR上的应用程序与Mongodb数据库。我使用Mongoid映射器。模型post.rb

代码语言:javascript
复制
class Post
  include Mongoid::Document

  field :title, :type => String
  field :text, :type => String

  embeds_many :comments
end

模型comment.rb

代码语言:javascript
复制
class Comment  
  include Mongoid::Document

  field :name, :type => String
  field :content, :type => String

  embedded_in :post, :inverse_of => :comments
end 

在数据库中,这篇带有一些评论的帖子有下面的结构:

代码语言:javascript
复制
{
   "_id": ObjectId("4ecbeacf65430f0cef000003"),
   "comments": {
     "0": {
       "name": "my name",
       "content": "example content",
       "_id": ObjectId("4ecbead365430f0cef000005") 
    },
     "1": {
       "name": "some name",
       "content": "example content",
       "_id": ObjectId("4ecbead665430f0cef000007") 
    },
     "2": {
       "name": "some name",
       "content": "example content",
       "_id": ObjectId("4ecbeada65430f0cef000009") 
    } 
  },
   "text": "example text",
   "title": "example title" 
}

例如,在数据库中有一些帖子和我的评论。我需要找到所有的帖子,其中"name": "my name",即我需要找到所有可编辑的帖子。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-11-23 23:56:12

它应该显示为注释数组,而不是散列。请参见下面的示例。

此外,根据mongoid文档,使用新的样式字段声明。

comment.rb:

代码语言:javascript
复制
class Comment
  include Mongoid::Document

  field :name, type: String
  field :content, type: String

  embedded_in :post
end

post.rb:

代码语言:javascript
复制
class Post
  include Mongoid::Document

  field :title, type: String
  field :text, type: String

  embeds_many :comments
end

Rails控制台:

代码语言:javascript
复制
p = Post.new(:title => "title", :text => "post")
c1 = Comment.new(:name => "Tyler", :comment => "Awesome Comment!")
c2 = Comment.new(:name => "Joe", :comment => "comment 2")
p.comments << c1
p.comments << c2
p.save

Mongo控制台:

代码语言:javascript
复制
> db.posts.findOne()
{
    "_id" : ObjectId("4ecd151d096f762149000001"),
"title" : "title",
"text" : "post body",
"comments" : [
            {
        "name" : "Tyler",
        "comment" : "Awesome Comment!",
        "_id" : ObjectId("4ecd1569096f762149000002")
    },
    {
        "name" : "Joe",
        "comment" : "comment 2",
        "_id" : ObjectId("4ecd157f096f762149000003")
    }
]}

然后,做你想要的查询,我想是"comments by me?":

代码语言:javascript
复制
> db.posts.findOne({"comments.name": "Tyler"})

另外,我将在comments.name字段中添加一个索引:

代码语言:javascript
复制
> db.posts.ensureIndex({"comments.name": 1})
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8240668

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档