In my collection there is field called as time and the format of this field is as follows :
time: “2019/05/02 00:00:00”.
I need to extract hours from this field and group them based on hour. I tried many things including ISODate(), new Date() but getting different errors. Below is my project block followed by one of the errors. Any help in this regard will be appreciated.
As you’re storing the time field as a string you can’t use the $hour operator directly. You will first need to convert the time to a Date type, which can be done using the $dateFromString operator as such:
@Gunjan_Gautam try it first using the mongo shell. I’m not sure what the output is you’re sharing but if you can adapt the following and share the results it might help:
// change COLLECTION to the name of your collection
db.COLLECTION.aggregate([
{ $limit: 1 },
{ $addFields: {
hour: {
$hour: {
$dateFromString: { dateString: "$time", format: "%Y/%m/%d %H:%M:%S" }
}
}
}}])
If your time field only contains data in this format then what @steevej wrote is correct. My example expected the date string to be in a 2019/05/02 00:00:00 format, however your latest example uses a different delimiter (- compared to /).