11

How dow I query comments greater than or less than a certain date...

Here is my Schema with Post model and a Comment model:

var mongoose = require('mongoose');
var should = require('should');

mongoose.connect("localhost","test_db");

var CommentSchema = new mongoose.Schema({
  content:    {type:String},
  created_at: {type:Date, default:Date.now}

});

var PostSchema = new mongoose.Schema({
  title:    {type:String},
  content:  {type:String},
  comments: [CommentSchema]

    });

var Post = mongoose.model('Post',PostSchema);
var Comment = mongoose.model('Comment',CommentSchema);

var post = new Post({title:"hello world",comments:[{content:"1st comment"},{content:"2nd comment"}]});
// I saved it! and then I query for it

  var id = "5045d5be48af9f040f000002";
  Post.find({ _id:id,
              "comments.created_at":{ $gte:(new Date())}
                },function(err,result){
    console.log(result);
  });

I need help with querying the embedded docs...

Ok I edited my code to give more detail.

This returns an empty array. So what I want or what I would expect is a Post with an empty comments array. But with this query I do not get a post at all. (when I exchange $gte with $lte I get (obviously) the post with its 2 comments).

But again how can I filter the details so according to my description above?

silverfighter
  • 6,762
  • 10
  • 46
  • 73

1 Answers1

21

Use dot notation to reach inside the embedded array docs. For example, to query for the Post comments with a created_at between date1 and date2:

Post.find({ "comments.created_at": { $gt: date1, $lt: date2 }}, function (err, docs) {
     ...
});

UPDATE

Thanks for the edit; now I understand that you're trying to to filter the comments of single post by their created_at date. You can't do that directly with MongoDB queries, but I believe you can do it with the 2.2 aggregation framework if you're at that version. Take a look at the discussion of this feature request on Jira for examples.

JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
  • cool thanks, and how would I do it for 1 Post {_id:1,"comments.created_a": {$lt:(new Date())}... ? – silverfighter Sep 03 '12 at 14:38
  • Right, you just add the `_id:1` property to your selector object. – JohnnyHK Sep 03 '12 at 14:45
  • thanks for your reply... is this related to embedded docs only would something like this be possible if I change the comments to a ref (like FK in sql db's)? – silverfighter Sep 04 '12 at 13:22
  • @silverfighter Right, the issue is because you're using an array of embedded comment docs in `Post` rater than a separate comments collection that you can query. – JohnnyHK Sep 04 '12 at 13:45