Mongoose查询嵌套文档的时间或多或少为某个日期

Mongoose query nested documents greater or less a certain date

本文关键字:日期 或多或少 时间 查询 嵌套 文档 Mongoose      更新时间:2023-09-26

如何查询大于或小于某个日期的注释。。。

这是我的模式与张贴模型和评论模型:

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);
  });

我需要帮助查询嵌入的文档。。。

好的,我编辑了我的代码以提供更多细节。

这将返回一个空数组。因此,我想要或期望的是一个带有空评论数组的Post。但有了这个问题,我根本没有得到一个职位。(当我用$gte交换$lte时,我(显然)得到了带有2条评论的帖子)。

但是,我如何根据我上面的描述过滤细节呢?

使用点表示法访问嵌入式数组文档内部。例如,要查询date1date2之间具有created_atPost注释:

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

更新

感谢您的编辑;现在我明白了,你试图通过他们的created_at日期来过滤单个帖子的评论。您不能直接使用MongoDB查询来实现这一点,但我相信,如果您使用的是2.2聚合框架,那么您可以使用该版本。举个例子,看看Jira上关于这个特性请求的讨论。