0

My database is structured as follows:

{ title : "My First Post", author: "Jane",
  comments : [{ by: "Abe", text: "First" },
              { by : "Ada", text : "Good post" } ]
}

I am having trouble writing out the following:

  • Get all posts on which Ada did not comment
  • Get all posts on which Abe commented "First"
  • Once a post has been found and stored in a post variable, display the text of the comment by Abe

Thanks.

1 Answer 1

5

Get all posts on which Ada did not comment

There is a $nin(stands for not in) operator in MongoDB you can write query like this:

db.my.collection.find({'comments.by': {$nin: ['Ada']}});

Get all posts on which Abe commented "First"

As far as comments are stored in array it's absolutely legal to access particular items by their index. To achieve this goal you can write following query:

db.my.collection.find({'comments.0.by': 'Abe'});

Once a post has been found and stored in a post variable, display the text of the comment by Abe

This depends on your client application how you present retrieved data.

5
  • Thanks. The post variable is a JSON object like the one presented in my question. How can I retrieve the text of the comment by Abe?
    – alste
    Dec 2, 2011 at 7:22
  • np. I guess: post.comments[0]
    – ioseb
    Dec 2, 2011 at 7:26
  • And if Abe was not the first commenter?
    – alste
    Dec 2, 2011 at 7:28
  • in this particular case you need to traverse .comments array and check "by" property. It's not possible to just retrieve comment by "Abe" from array.
    – ioseb
    Dec 2, 2011 at 7:32
  • An optimization is also to use the fields parameter on the find to only retrieve the comments. This will speed the query up as you won't have to pull back as much data.
    – christkv
    Dec 3, 2011 at 13:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.