How to find all date-ranges overlapping another date-range in MongoDB? -


everyone!

i have record of type:

{     start: 2015-03-27t15:00:00.000z,     end: 2015-03-27t17:00:00.000z } 

and trying find in database crossing periods.

{     start: 2015-03-27t15:30:00.000z,     end: 2015-03-27t16:00:00.000z } 

i scheduling system. , not there time occupied.

i believe trying find documents overlapping date ranges. in other words document start or end dates falls in between given date range.

you can achieve little bit match , logic.

let's assume have 2 documents in collection

{      "_id" : objectid("56f692730c96eddb0a2c287e"),      "start" : "2015-03-27t15:00:00.000z",      "end" : "2015-03-27t17:00:00.000z" } {      "_id" : objectid("56f6928c0c96eddb0a2c287f"),      "start" : "2015-03-27t16:00:00.000z",      "end" : "2015-03-27t27:00:00.000z" } 

when execute following piece of code

var startdate = "2015-03-27t20:00:00.000z"; var enddate = "2015-03-27t21:00:00.000z";  var findoverlapingdates = function(startdate, enddate){   return db.collection.find({      $or: [         {$and: [           {start:{$gte: startdate}}, {start:{$lte: enddate}}         ]},         {start:{$lte: startdate}, end:{$gte: startdate}}      ]   }); };  printjson(findoverlapingdates(startdate, enddate).toarray()); 

i get

[     {         "_id" : objectid("56f6928c0c96eddb0a2c287f"),          "start" : "2015-03-27t16:00:00.000z",          "end" : "2015-03-27t27:00:00.000z"     } ] 

which overlapping document given date range. hope makes sense. best performance, i'll recommend having index on both start , end fields.


Comments