我有一个集合
,其中包含特定操作的serviceDate
字段。
我需要查找给定的日期范围是否有缺少的 serviceDate
,以及如果发现 MongoDB 中的日期范围之间缺少 serviceDate 日期
的返回列表。
我的收藏的 JSON 示例如下。
{
"_id" : ObjectId("5cefdb46bfbe1c0001f38413"),
"category" : "RENT",
"serviceDate" : ISODate("2019-06-15T05:30:00.000+05:30")
},
{
"_id" : ObjectId("5cefdb46bfbe1c0001f38412"),
"category" : "RENT",
"serviceDate" : ISODate("2019-06-14T05:30:00.000+05:30")
},
{
"_id" : ObjectId("5cefdb46bfbe1c0001f38411"),
"category" : "RENT",
"serviceDate" : ISODate("2019-06-13T05:30:00.000+05:30")
}
示例:
案例1:
如果集合有 10 个文档,并且服务日期从 2019 年 6 月 1 日到 2019 年 6 月 10 日开始。
在我的查询中,我将 2019 年 6 月 4 日传递到 2019 年 6 月 7 日,结果应该为 null。
案例2:
如果集合有 9 个文档,并且服务日期从 1-June-2019 到 10-June-2019,但缺少 6-June-2019。
在我的查询中,我将 2019 年 6 月 4 日传递到 2019 年 6 月 7 日,结果应该是 2019 年 6 月 6 日。
案例3:
如果集合有 9 个文档,并且服务日期从 1-June-2019 到 10-June-2019,但缺少 6-June-2019、5-June-2019。
在我的查询中,我将 2019 年 6 月 4 日传递到 2019 年 6 月 7 日,结果应该是 2019 年 6 月 6 日和 2019 年 6 月 5 日。
最佳答案
您需要首先查找您在查询中传递的日期范围之间的所有日期。你必须使用一些 javascript 技巧来做到这一点。
function getDates(startDate, stopDate) {
var dateArray = []
var currentDate = moment(startDate)
var stopDate = moment(stopDate)
while (currentDate <= stopDate) {
dateArray.push(moment(currentDate).format('YYYY-MM-DD'))
currentDate = moment(currentDate).add(1, 'days')
}
return dateArray
}
const dateArray = getDates(startDate, startDate)
//Output will be something like
dateArray = [ "2018-09-01", "2018-09-02", "2018-09-03", "2018-09-04", "2018-09-05" ]
现在您可以使用聚合来查找 $setDifference
获取不存在的 serviceDates
。
db.collection.aggregate([
{ '$match': {
'serviceDate': { '$gte': startDate, '$lte': endDate }
}},
{ '$group': {
'_id': null,
'dates': { '$push': { '$dateToString': { 'date': '$serviceDate', 'format': '%Y-%m-%d' }}}
}},
{ '$project': {
'missingDates': { '$setDifference': [dateArray, '$dates'] }
}}
])
关于javascript - 查找 MongoDB 中一系列日期中缺失的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56388708/