Mongodb今天按日期查找创建的结果 [英] Mongodb find created results by date today

查看:147
本文介绍了Mongodb今天按日期查找创建的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有此查询以获取当月的结果.但是我想得到今天的结果.

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?

推荐答案

您的开始日期对象应将当前日期时间设置为00:00:00.000(毫秒精度),并将今天的时间设置为23:59:59.999:

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:

var start = new Date();
start.setHours(0,0,0,0);

var end = new Date();
end.setHours(23,59,59,999);

然后像往常一样在您的MongoDB查询运算符中传递修改后的日期对象:

Then pass the modified date objects as usual in your MongoDB query operator:

db.posts.find({created_on: {$gte: start, $lt: end}});

如果您使用的是 momentjs 库,则可以使用 endOf() 方法,用于当前时刻的当前日期对象,并将字符串'day'作为参数传递:

If you are using the momentjs library, this can be done by using the startOf() and endOf() methods on the moment's current date object, passing the string 'day' as arguments:

var start = moment().startOf('day'); // set to 12:00 am today
var end = moment().endOf('day'); // set to 23:59 pm today

这篇关于Mongodb今天按日期查找创建的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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