Dileep Paul
Dileep Paul

Reputation: 167

Convert string time to date in mongodb

I have an aggregate query in which i am splitting a field value and trying to create a date using $dateFromParts from values in split array, unfortunately i am getting below error. Since I am using M0 instances of Mongo Altas for development purpose and its version is 3.6, i cannot use $convert and $toInt features of v4. Please suggest a solution.

'hour' must evaluate to an integer, found string with value

{
      {  
            $addFields: {
                departure_time: { $split: ["$timings.departure", ":"] }  
            }
        }
        ,
        {
            $project: { 
                departure_date: { $dateFromParts: { 'year': dt.getUTCFullYear(), 'month': dt.getUTCMonth(), 'day': dt.getUTCDate(), 'hour': { $arrayElemAt: ["$departure_time", 0] }, 'minute': { $arrayElemAt: ["$departure_time", 1] } } }
            }
        }
}

Upvotes: 1

Views: 536

Answers (1)

Ashh
Ashh

Reputation: 46461

You can try using $dateFromString in mongodb 3.6

db.collection.aggregate([
  { "$project": {
    "departure_date": {
      "$dateFromString": {
        "dateString": { "$concat": ["2018-09-19", "T", "$timings.departure"] }
      }
    }
  }}
])

Upvotes: 1

Related Questions