Mongodb按今天的日期查找创建的结果

xzlaal3s  于 2023-01-04  发布在  Go
关注(0)|答案(3)|浏览(132)

我有这个查询,以获得每月的结果。但我想得到今天的结果。

var start = new Date(2010, 11, 1);
var end = new Date(2010, 11, 30);

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

做这件事的最好方法是什么?

csbfibhn

csbfibhn1#

您的start date对象应该将当前日期时间的小时数设置为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 date utility库,则可以通过对dayjs的当前日期对象使用startOf()endOf()方法,并将字符串'day'作为参数传递来完成此操作:

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

也可以按如下方式使用$expr

db.posts.find({
    $expr: {
        $eq: [
            { $dateToString: { format: '%Y-%m-%d', date: '$$NOW' } },
            { $dateToString: { format: '%Y-%m-%d', date: '$created_on' } },
        ],
    },
})
ndh0cuux

ndh0cuux2#

溶液
要查找今天的结果或日期之间的数据,请使用以下命令:

    • NodeJS :**
// Date format YYYY-MM-DD
// Suppose you want to look for 1 day data between 2021-12-27 00:00:00 and 2021-12-28 00:00:00
let start = new Date("2021-12-27");
let end = new Date("2021-12-28");

// "created_on" can be any field with a date 
db.posts.find({created_on: {$gte: start, $lt: end}});

这也适用于Mongo Shell

db.posts.find({created_on: {$gte: new ISODate("2021-12-27T00:00:00.000Z"), $lt: new ISODate("2021-12-28T00:00:00.000Z")}})

另一种方式:

// 27th half day
db.posts.find({created_on: {$gte: new Date("2021-12-27T00:00:00.000Z"), $lt: new Date("2021-12-27T12:00:00.000Z")}})

参考

find-Select / filter data
$gte-Greater Than / Equal
$lt-Lower Than

hc2pp10m

hc2pp10m3#

// Get Today Start Date and End Date
  let startOfDay = new Date();
  startOfDay.setHours(0, 0, 0, 0);
  let endOfDay = new Date();
  endOfDay.setHours(23, 59, 59, 999);

  // Get Yesterday Start Date and End Date
  let startOfYesterday = new Date();
  startOfYesterday.setDate(startOfYesterday.getDate() - 1);
  startOfYesterday.setHours(0, 0, 0, 0);
  let endOfYesterday = new Date();
  endOfYesterday.setDate(endOfYesterday.getDate() - 1);
  endOfYesterday.setHours(23, 59, 59, 999);

  // Get Last Month Start Date and End Date
  let startOfPreviousMonth = new Date();
  startOfPreviousMonth.setMonth(startOfPreviousMonth.getMonth() - 1);
  startOfPreviousMonth.setDate(1);
  startOfPreviousMonth.setHours(0, 0, 0, 0);
  let endOfPreviousMonth = new Date();
  endOfPreviousMonth.setMonth(endOfPreviousMonth.getMonth() - 1);
  let lastDayOfPreviousMonth = new Date(
    endOfPreviousMonth.getFullYear(),
    endOfPreviousMonth.getMonth() + 1,
    0
  );
  endOfPreviousMonth.setDate(lastDayOfPreviousMonth.getDate());
  endOfPreviousMonth.setHours(23, 59, 59, 999);

相关问题