我有一个collection,它包含一个特定操作的serviceDate字段。我需要找到一个给定的日期范围,是否有任何serviceDate丢失,如果找到,则在MongoDB的日期范围之间缺少serviceDate dates的返回列表。我收集的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个文档,则为,serciceDate从2009年6月1日至2019年6月10日至2019年6月10日开始。在我的查询中,我将传递4-6-2019到7-6-2019,结果应该为null。
案例2:如果集合有9个文档,而serciceDate从2009年6月1日至2019年6月10日到2019年6月10日至2019年6月,则缺少。在我的查询中,我传递的是4-6-2019到7-6-2019,结果应该是6-6-2019。
案例3:如果集合有9个文档,而serciceDate从2009年6月1日至2019年6月10日至2019年6月10日至2019年6月至2019年,则缺失。在我的查询中,我传递的是4-6-2019到7-6-2019,结果应该是6-6-2019和5-6-2019。
发布于 2019-05-31 04:54:19
您需要首先查找在查询中传递的日期范围之间的所有日期。这和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'] }
}}
])https://stackoverflow.com/questions/56388708
复制相似问题