首页 > 解决方案 > 在猫鼬中查询两个日期并返回匹配的文档?

问题描述

我有一个 mongoose 集合,其架构如下所示:

"date_from": {type: Date, required: true},
"date_to": {type: Date, required: true},
"num_guests": {type: Number, required: true},
"children": {type: Number, required: true},

现在我必须根据我提供的日期搜索介于“date_from”到“date_to”范围内的文档。

现在,我想出了这段代码,它可以完成我需要的大部分工作。

 model.find({_id: req.body._id,
                $and:[{date_from: {$gte: "2020-04-26T06:50:45.079+00:00",$lte: "2020-05-01T06:50:45.079+00:00"}},
{date_to: {$lte: "2020-05-01T06:50:45.079+00:00"}}]
            })

但是我在以下情况下遇到了此代码的问题:在我的集合中有一个文档"date_from": "2020-04-04"必须"date_to":"2020-04-08". 现在,当我使用 and 查询时$gte: "2020-04-03"$lte: "2020-04-09"我得到了文档,但是当我将它更改为$gte: "2020-04-05"and时$lte: "2020-04-09",我收到了一个空数组。但是我仍然需要获取该文档,因为从技术上讲它仍然在$gte: "2020-04-05"and$lte: "2020-04-09"中。我该怎么做?

这种情况可以通过以下方式得到最好的解释:

我现在预订了 12-04-2020 至 24-04-2020 的酒店房间,如果有人查找 16-04-2020 至 20-04-2020 之间的所有预订,那么他们应该会看到在 12 至 2020 之间进行的预订24.

我查看了其他相关问题以找到答案,但没有找到任何答案。

标签: javascriptmongodbdatemongoosemongodb-query

解决方案


推荐阅读