Javascript Mongoose 查询嵌套文档或多或少某个日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12249223/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Mongoose query nested documents greater or less a certain date
提问by silverfighter
How dow I query comments greater than or less than a certain date...
我如何查询大于或小于某个日期的评论...
Here is my Schema with Post model and a Comment model:
这是我的带有 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?
但是,如何根据我上面的描述过滤详细信息?
回答by JohnnyHK
Use dot notationto reach inside the embedded array docs. For example, to query for the Post
comments with a created_at
between date1
and date2
:
使用点符号进入嵌入式数组文档。例如,要查询Post
带有和created_at
之间的评论:date1
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 requeston Jira for examples.
感谢您的编辑;现在我知道您正在尝试按created_at
日期过滤单个帖子的评论。你不能直接用 MongoDB 查询来做到这一点,但我相信如果你在那个版本中,你可以用 2.2 聚合框架来做到这一点。请查看Jira上对此功能请求的讨论以获取示例。