Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose query nested documents greater or less a certain date

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?

like image 214
silverfighter Avatar asked Sep 03 '12 13:09

silverfighter


1 Answers

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.

like image 102
JohnnyHK Avatar answered Nov 15 '22 14:11

JohnnyHK