Eugene
Eugene

Reputation: 689

Mongoid querying

I have some application on RoR with Mongodb database. I use Mongoid mapper. Model post.rb

class Post
  include Mongoid::Document

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

  embeds_many :comments
end

Model comment.rb

class Comment  
  include Mongoid::Document

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

  embedded_in :post, :inverse_of => :comments
end 

In database this post with some comment has next structure:

{
   "_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" 
}

And, for example, in database was a few posts with my comments. I need to find all posts, where "name": "my name", i.e. I need to find all editable by me posts.

Upvotes: 1

Views: 522

Answers (1)

Tyler Brock
Tyler Brock

Reputation: 30176

It should appear as a array of comments instead of a hash. See my example below.

Also, as per the mongoid docs use the new style field declarations.

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

Rails Console:

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 Console:

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

Then, to do the query you want, which I think was "comments posted by me?":

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

Also, I would add an index to the comments.name field:

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

Upvotes: 3

Related Questions