您的开始日期对象应保存当前日期时间小时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);
然后像往常一样在 MongoDB 查询运算符中传递修改后的日期对象:
db.posts.find({created_on: {$gte: start, $lt: end}});
如果您正在使用dayjs 日期实用程序 https://day.js.org/库,这可以通过使用来完成startOf() https://day.js.org/docs/en/manipulate/start-of#docsNav and endOf() https://day.js.org/docs/en/manipulate/end-ofdayjs 当前日期对象的方法,传递字符串'day'
作为参数:
const start = dayjs().startOf('day'); // set to 12:00 am today
const end = dayjs().endOf('day'); // set to 23:59 pm today
您还可以使用$expr https://www.mongodb.com/docs/manual/reference/operator/query/expr/如下:
db.posts.find({
$expr: {
$eq: [
{ $dateToString: { format: '%Y-%m-%d', date: '$$NOW' } },
{ $dateToString: { format: '%Y-%m-%d', date: '$created_on' } },
],
},
})