在MongoDB中基于时间段获取数据

如何按时间段按date显示计数数据的数量。

我们有插槽

[{'startTime':“2017-04-20T08:30:00.000Z”,“endTime”:“2017-04-20T09:30:00.000Z”},

{'startTime':“2017-04-20T09:30:00.000Z”,“endTime”:“2017-04-20T10:30:00.000Z”},

{'startTime':“2017-04-20T10:30:00.000Z”,“endTime”:“2017-04-20T18:30:00.000Z”}]

input

[{ "createdAt" : ISODate("2017-04-20T09:20:00.167Z"), }, { "createdAt" : ISODate("2017-04-20T14:20:00.167Z") }, { "createdAt" : ISODate("2017-04-20T11:20:00.167Z") }, { "createdAt" : ISODate("2017-04-20T14:20:00.167Z") }, { "createdAt" : ISODate("2017-04-20T12:20:00.167Z") }] 

以这种格式显示数据

产量

[{'startTime':“2017-04-20T08:30:00.000Z”,“endTime”:“2017-04-20T09:30:00.000Z”,“count”:1},

{'startTime':“2017-04-20T09:30:00.000Z”,“endTime”:“2017-04-20T10:30:00.000Z”,“count”:0},

{'startTime':“2017-04-20T10:30:00.000Z”,“endTime”:“2017-04-20T18:30:00.000Z”},'count':4]

 var tempData = [], for(var i = 0; i <inputData.length ; i++){ var condition = { '$sum':{'$cond': [{'$and': [{'$gte': ['$checkinData.time', new Date(inputData[i].startTime)]}, {'$lt' : ['$checkinData.time', new Date(inputData[i].endTIme)]} ]},1,0] } } tempData.push(condition); } 

您可以使用MongoDB的$gte (大于或等于), $lte (小于或等于), $gt (大于)和$lt (小于)来指定date范围。 您可以在$gte/$gt指定“from”date,在$lte/$lt指定“to”date。

所以你的查询应该看起来像这样 –

 db.collection.count({createdAt: {$gte: "your from date in ISO date object format", $lte: "your to date in ISO date object format"}}, function (err, count){ //whatever you wanna do with count }) 

要么

 db.collection.find({createdAt: {$gte: "your from date in ISO date object format", $lte: "your to date in ISO date object format"}}).count(function (err, count){ //whatever you wanna do with count }) 

对于每一个时间段,你将不得不循环运行。 所以就像一个例子,它看起来像 –

 db.collection.find({createdAt: {$gte: timeRangeArr[i].startTime, $lte: timeRangeArr[i].endTime}}).count(function (err, count){ //whatever you wanna do with count })