我认为没有办法在 Mongo 聚合框架中动态匹配当前日期。
在您的服务器端应用程序中,您必须动态计算开始日期和结束日期,然后将其传递给您的 $match。
下面是一个获取本周开始和结束日期的示例函数(假设开始=星期日和结束=星期六)。
const SUNDAY_DAY_NUMBER = 0;
const SATURDAY_DAY_NUMBER = 6;
/**
* @example
* const dateQuery = getDateQueryForCurrentWeek();
* const matchObject = { CREATED_ON: dateQuery };
* const findResult = db.getCollection('collection').aggregate([{ $match: matchObject }]).toArray();
*/
const getDateQueryForCurrentWeek = () => {
const now = new Date();
const numDaysToBeginningOfWeek = SUNDAY_DAY_NUMBER - now.getDay();
const numDaysToEndOfWeek = SATURDAY_DAY_NUMBER - now.getDay();
const firstDayOfCurrentWeek = new Date(
now.getFullYear(),
now.getMonth(),
now.getDate() + numDaysToBeginningOfWeek,
0,
0,
0,
0
);
const lastDayOfCurrentWeek = new Date(
now.getFullYear(),
now.getMonth(),
now.getDate() + numDaysToEndOfWeek,
24,
0,
0,
-1
);
const query = {
$gte: firstDayOfCurrentWeek,
$lte: lastDayOfCurrentWeek
};
return query;
};