简体   繁体   English

Mongoose查询嵌套文档或多或少某个日期

[英]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: 这是我的Schema with Post模型和Comment模型:

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). (当我用$ lte兑换$ gte时,我得到(显然)有2条评论的帖子)。

But again how can I filter the details so according to my description above? 但是,我如何根据上面的描述过滤细节呢?

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 : 例如,要在date1date2之间查询带有created_atPost注释:

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

UPDATE 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. 现在我知道你试图通过created_at日期来过滤单个帖子的评论。 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. 你不能直接使用MongoDB查询,但我相信你可以使用2.2聚合框架,如果你在那个版本。 Take a look at the discussion of this feature request on Jira for examples. 有关示例, 查看Jira上此功能请求的讨论。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM