MongoDB aggregate by date in string format doesn't work

1.1k views Asked by At

I have a mongodb collection with a date field "localHitDate" which is a string property and I'd like to aggregate on this date. So, I have to convert my date string into a BSON date type, but it did not work :

db.log.aggregate([
{ $match:{"category":"log"}},
{ $group: 
    {
    _id:{
        location : "$location",
        year : { $year : ISODate(localHitDate) },        
        month : { $month : ISODate(localHitDate) },        
        day : { $dayOfMonth : ISODate(localHitDate) }
        },
    total: {$sum:1}, 
    payload: {$sum:"$technicalData.payload"}
    }
},
{ $sort: { total : -1} }
])

I have this error : ReferenceError: localHitDate is not defined (shell):7

I tried ISODate($localHitDate) but I still have an error.

Do you know how to do this?

Thank you

1

There are 1 answers

0
Fred Mériot On BEST ANSWER

I solved my problem converting the "localHitDate" from string type to date type (ISODate)