node.js Mongodb今天按日期查找创建的结果
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29327222/
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
Mongodb find created results by date today
提问by Rex Adrivan
I have this query to get results on month. But I wanted to get the results of today.
我有这个查询来获得月的结果。但我想得到今天的结果。
var start = new Date(2010, 11, 1);
var end = new Date(2010, 11, 30);
db.posts.find({created_on: {$gte: start, $lt: end}});
What is the best way to do this?
做这个的最好方式是什么?
回答by chridam
Your start date object should hold the current date time hours at 00:00:00.000(milliseconds precision) and set the hours for today's date to 23:59:59.999:
您的开始日期对象应将当前日期时间小时保持在00:00:00.000(毫秒精度)并将今天日期的小时数设置为23:59:59.999:
var start = new Date();
start.setHours(0,0,0,0);
var end = new Date();
end.setHours(23,59,59,999);
Then pass the modified date objects as usual in your MongoDB query operator:
然后像往常一样在 MongoDB 查询运算符中传递修改后的日期对象:
db.posts.find({created_on: {$gte: start, $lt: end}});
If you are using the momentjslibrary, this can be done by using the startOf()and endOf()methods on the moment's current date object, passing the string 'day'as arguments:
如果您使用的是momentjs库,则可以通过在 moment 的当前日期对象上使用startOf()和endOf()方法,将字符串'day'作为参数传递来完成:
var start = moment().startOf('day'); // set to 12:00 am today
var end = moment().endOf('day'); // set to 23:59 pm today

