Mongoose query nested documents greater or less a certain date


Question

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?

1
11
9/4/2012 10:45:21 AM

Accepted Answer

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.

19
9/4/2012 12:33:22 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon