2011-11-23 5 views
1

RoG에 Mongodb 데이터베이스가있는 응용 프로그램이 있습니다. 몽고 매퍼를 사용합니다. 모델 post.rb몽고 이드 쿼리

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

: 또한

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

, 나는 comments.name 필드에 인덱스를 추가 할을 Comments 객체가 객체의 배열이 아니어야합니까? 임의의 이름을 가진 하위 객체의 객체가 아닌가? 스키마 구조를 다시 살펴 보겠습니다. – 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.ensureIndex({"comments.name": 1}) 
+0

나는 당신이 쓴 것을했지만 데이터베이스 구조는 변하지 않습니다. – Eugene

+0

최신 레일 및 몽고 이드? –

+0

레일 3.1.1, 몽고이 2.3.4 – Eugene