I have several records on the mongoDB. I need to know the no of records present on each date.I know that we can get the date from _id field.Please help me how to do this ?
1 Answer
You can do it with MongoDB Map-Reduce feature, using ObjectID::getTimestamp() method to determine insertion time.
Here is an example of doing so:
db.runCommand({
mapreduce: 'collection',
map: function() {
var created = this._id.getTimestamp();
var date = created.toISOString().slice(0, 10);
return emit(date, 1);
},
reduce: function(key, vals) {
return Array.sum(vals);
},
out: {
inline: 1
}
})
I'm using Date::toISOString() method to convert insertion date into ISO date string
2014-07-21T12:39:21.000Z
and String::slice() method to take first 10 characters of it
2014-07-21
The resulting output of this Map-Reduce task should look like this:
[
{
"_id" : "2014-07-21", // date
"value" : 100011 // number of documents
},
...
]
3 Comments
prashantas
It seems fine. I want to achieve the same in a .js file.The output should be of the format date1, count date2,count date3,count etc.
Leonid Beschastny
@prashantas What do you mean by
.js file? Do you mean node.js script, or just a .js file executed in mongo shell?prashantas
It is just a .js file. Anyway I found the solution with your help.Thanks a lot.