I'm trying to calculate frequency of documents in my db based on 10 seconds intervals.
this is how my database objects look like:
[
{
created_at: "2014-03-31T22:30:48.000Z",
id: 450762158586880000,
_id: "5339ec9808eb125965f2eae1"
},
{
created_at: "2014-03-31T22:30:48.000Z",
id: 450762160407597060,
_id: "5339ec9808eb125965f2eae2"
},
{
created_at: "2014-03-31T22:30:49.000Z",
id: 450762163482017800,
_id: "5339ec9908eb125965f2eae3"
},
{
created_at: "2014-03-31T22:30:49.000Z",
id: 450762166367707140,
_id: "5339ec9908eb125965f2eae4"
},
{
created_at: "2014-03-31T22:30:50.000Z",
id: 450762167412064260,
_id: "5339ec9a08eb125965f2eae5"
}
]
I have managed to display the frequency in the given interval, but I would like to get that for every 10 seconds. So preferably my JSON would look like:
[
{
time_from: "2014-03-31T22:30:48.000Z",
time_to: "2014-03-31T22:30:58.000Z",
count: 6
},
{
time_from: "2014-03-31T22:30:58.000Z",
time_to: "2014-03-31T22:31:08.000Z",
count: 3
},
{
time_from: "2014-03-31T22:31:08.000Z",
time_to: "2014-03-31T22:31:18.000Z",
count: 10
},
{
time_from: "2014-03-31T22:31:18.000Z",
time_to: "2014-03-31T22:31:28.000Z",
count: 1
},
{
time_from: "2014-03-31T22:31:28.000Z",
time_to: "2014-03-31T22:31:38.000Z",
count: 3
}
]
this is what I have done so far:
exports.findAll = function (req, res) {
db.collection(collection_name, function (err, collection) {
collection.find().toArray(function (err, items) {
collection.find().sort({"_id": 1}).limit(1).toArray(function (err, doc) {
var interval = 100000; // in milliseconds
var startTime = doc[0].created_at;
var endTime = new Date(+startTime + interval);
collection.aggregate([
{$match: {"created_at": {$gte: startTime, $lt: endTime}}},
{$group: {"_id": 1, "count":{$sum: 1}}}
], function(err, result){
console.log(result);
res.send(result);
});
});
})
});
};
and this is the result of that:
[
{
_id: 1,
count: 247
}
]
EDIT:
collection.aggregate([
{ $group: {
_id: {
year: { '$year': '$created_at'},
month: {'$month': '$created_at'},
day: {'$dayOfMonth': '$created_at'},
hour: {'$hour': '$created_at'},
minute: {'$minute': '$created_at'},
second: {'$second': '$created_at'}
},
count: { $sum : 1 }
} }
], function (err, result) {
console.log(result);
res.send(result);
});
which results in:
[
{
_id: {
year: 2014,
month: 3,
day: 31,
hour: 22,
minute: 37,
second: 10
},
count: 6
}, ...
new progress, now how would I display it in 10 seconds interval?