2011-11-23 92 views
1

我在MongoDB数据库的RoR上有一些应用。我使用Mongoid映射器。型号post.rbMongoid查询

class Post 
    include Mongoid::Document 

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

    embeds_many :comments 
end 

型号comment.rb

class Comment 
    include Mongoid::Document 

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

    embedded_in :post, :inverse_of => :comments 
end 

在数据库这篇文章的一些评论有一个结构:

{ 
    "_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",即我需要找到所有可编辑的帖子。

+0

你的评论对象不应该是对象的数组吗?不是具有任意名称的子对象的对象?我会重新看看你的架构体系结构。 – Petrogad

回答

3

它应该显示为一个注释数组而不是散列。看我下面的例子。

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

comment.rb:

class Comment 
    include Mongoid::Document 

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

    embedded_in :post 
end 

post.rb:

class Post 
    include Mongoid::Document 

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

    embeds_many :comments 
end 

滑轨控制台:

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 

蒙戈控制台:

> 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") 
    } 
]} 

然后,做你想做的查询,我认为这是“发表的评论通过我吗?”:

> db.posts.findOne({"comments.name": "Tyler"}) 

另外,我想一个索引添加到comments.name领域:

> db.posts.ensureIndex({"comments.name": 1}) 
+0

我做了你写的,但数据库结构不变。 – Eugene

+0

最新的导轨和mongoid? –

+0

rails 3.1.1,mongoid 2.3.4 – Eugene