猫鼬查询嵌套文档或多或少的某个日期 [英] Mongoose query nested documents greater or less a certain date

查看:70
本文介绍了猫鼬查询嵌套文档或多或少的某个日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何查询大于或小于特定日期的评论...

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

这是我的带有Post模型和Comment模型的架构:

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.

这将返回一个空数组.所以我想要或期望的是一个带有空评论数组的帖子.但是用这个查询我什么都没有得到. (当我将$ gte与$ lte交换时,(显然)该帖子带有2条评论).

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?

推荐答案

使用点符号以进入嵌入式数组文档的内部.例如,要查询Postdate1date2之间的created_at注释:

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

更新

感谢您的修改;现在,我了解到您正在尝试按created_at日期过滤单个帖子的评论.您不能直接使用MongoDB查询来做到这一点,但是我相信如果您使用的是2.2版本的聚合框架,则可以做到这一点.看看有关Jira上功能请求的讨论.

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.

这篇关于猫鼬查询嵌套文档或多或少的某个日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆