javascript - 仅在 mongodb 聚合中匹配时间
问题描述
我每天将开放时间存储为一系列班次,如下所示:
{
Monday: [{
startTime: {
hour: 8,
minute: 50
},
endTime: {
hour: 20,
minute: 30
}
}];
}
我正在尝试使用$match
如下所示的 MongoDB 聚合运算符检索班次开始和结束之间的文档:
{
$match: {
'Monday.startTime.hour': { // ex: 8
$lte: parseInt(now.format('HH'), 10), // now hours: 18
},
'Monday.startTime.minute': { // ex: 50
$lte: parseInt(now.format('mm'), 10), // now minutes: 40
},
'Monday.endTime.hour': { // ex: 20
$gte: parseInt(now.format('HH'), 10), // now hours: 18
},
'Monday.endTime.minute': { // ex: 30
$gte: parseInt(now.format('mm'), 10), // now minutes: 40
},
}
}
但问题是我们有一个如下图所示的移位示例, 第一个匹配条件:
'Monday.startTime.hour': {
$lte: parseInt(now.format('HH'), 10),
}
将通过,因为 8 小于 18。
但与分钟部分匹配的第二个匹配条件:
'Monday.startTime.minute': { // ex: 50
$lte: parseInt(now.format('mm'), 10), // now minutes: 40
},
将失败,因为 50 大于 40
虽然在现实生活08:50
中18:40
解决方案
我能够通过首先使用比较小时数来解决这个问题,$and
运算$or
符参见下面的解释代码:
{
$and: [ // grouping two conditions that now time needs to be between the start and the end of the shift.
{
$or: [ // compare the start time hour of the shift first
{
'Monday.startTime.hour': {
$lt: parseInt(now.format('HH'), 10),
},
},
{
$and: [ // if the upper condition didn't work will need to compare hours and minutes
{
'Monday.startTime.hour': {
$lte: parseInt(now.format('HH'), 10),
},
},
{
'Monday.startTime.minute': {
$lte: parseInt(now.format('mm'), 10),
},
},
],
},
],
},
{
$or: [ // compare the end time hour of the shift first
{
'Monday.endTime.hour': {
$gt: parseInt(now.format('HH'), 10),
},
},
{
$and: [ // if the upper condition didn't work will need to compare hours and minutes
{
'Monday.endTime.hour': {
$gte: parseInt(now.format('HH'), 10),
},
},
{
'Monday.endTime.minute': {
$gte: parseInt(now.format('mm'), 10),
},
},
],
},
],
},
];
}
推荐阅读
- python - 百分比差异计算
- python - Python Dython 更改 x 和 y 标签字体大小
- asp.net - IdentityServer4 在 Azure 的 Linux Web 应用程序中加载证书
- npm - 纱线从 NX 开始 - react-app-rewired 上的错误:
- ios - SwiftUI - 如何让视图离开其父容器
- vba - 如何输出我的数据库中的所有表数,但不包括隐藏表和系统表?
- performance - 提高对两个大数组求和的 Matlab 代码速度
- firebase - Setting up Firebase database data/rules to make user's post publicly viewable
- java - 需要对同步关键字进行说明
- loss-function - 添加具有恒定零输出的额外损失会改变模型收敛