I have a mongodb database where each row of the document has a date field (format ISO date).
I am trying to access hours and minutes in the date field and, for each minute of each hour, show the number of rows (notice that can be multiple rows for a minute). The output would be something like this:
11:20 5
11:41 1
13:20 8
15:30 11
Where the first column is the time (hour:minutes), and the second column the number of rows corresponding that time.
This is the command I am executing in mongodb:
db.user.aggregate([{$group: {_id: {hora: {$hour: '$created_at'}, minuto: {$minute: '$created_at'}}, total: {$sum: 1}}}])
where 'hora' is the field showing the hour and 'minuto' the field showing minutes.
This is the message I get:
It looks like you are not storing the date as ISODate
, but rather as a string with ISODate format.
When you run the find
query, it should be showing
"created_at" : ISODate("2016-11-01T11:46:03.000Z")
and not:
"created_at" : "2016-11-01T11:46:03.000Z"
The code you have written is correct.
You will need to convert your strings to ISODates.
You can fire this query in your mongoshell:
db.user.find().forEach(function(doc){
doc.created_at = new Date(created_at)
db.user.save(doc);
})