Mongodb find created results by date today

社会主义新天地 提交于 2019-11-26 19:48:08

问题


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?


回答1:


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

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

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

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


来源:https://stackoverflow.com/questions/29327222/mongodb-find-created-results-by-date-today

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!