我的集合中有字段 LAST_DATE_LIVE 字段,并且该值以 DD/MM/YYYY HH:mm:ss 格式保存为 string,例如:"06/12/2021 03:30: 00".
我的 API 中有一个过滤器,它接收的值为 “DD/MM/YYYY”(过滤器中不允许使用时间)和范围“DD/MM/YYYY-DD/MM/YYYY”)。我正在使用管道聚合。
这是查询的部分:
queryFilter = {
$and: [
{
$or: [
{
'LAST_DATE_LIVE': hasInterval ? { $gte: startDate, $lte: endDate } : { $regex: `^${startDate}` }
}
]
}
]
};
startDate 有一个值,正如我在 DD/MM/YYYY 格式中提到的,endDate 也是如此。
当我没有范围时,查询运行良好,问题出在范围中。 关于如何做到这一点有什么想法吗?
不确定您希望如何处理时间部分(例如,结束日期
2021-06-14
表示午夜或 11:59:59),但一般来说,如果您使用真实日期而不是 DD/MM/YYYY
字符串,这很容易做到.
sd = new ISODate('2021-06-13');
ed = new ISODate('2021-06-14');
c=db.foo.aggregate([
{$match: {$expr:
// The $dateFromString function is rather "long" so instead of
// calling it twice, use $let to set up a converted
// value once and use it in the $and:
{$let: {
vars: {'xd': {$dateFromString: {
dateString: '$LAST_DATE_LIVE',
format: '%m/%d/%Y %H:%M:%S'}} },
in: {$and:[ {$gte:['$$xd',sd]}, {$lte:['$$xd',ed]} ]}
}}
}}
]);