Home > other >  how to store hh(hour):mm(minutes) time in mongodb
how to store hh(hour):mm(minutes) time in mongodb

Time:09-26

Currently I am making scheduling system and storing information in mongodb

partial of my model looks like this

{
 timings: [{from: "00:00", to: "01:00"}],
 weekend: [0, 5, 6]
}

I am not sure if this will be good in the long run can you please help me decide how to better store time in my documents

CodePudding user response:

MongoDB does not have any time/interval data type, so you have to build your own solution. Some general notes:

Use week days according to ISO-8601 standard, i.e. first day (1) of week is Monday. Then it will be easier to create a Date value with $dateFromParts. For hour values use always 24-hour format.

You may consider to store times as

{from: {hour: 0, minute: 0}, to: {hour: 13, minute: 0}}

Otherwise, when you have to create Date value (e.g. for comparison), then it would be:

{
    $dateFromParts : {
        ...,
        hour: { $toInt: { $arrayElemAt: [ { $split: [ "$from", ":" ] }, 0 ] } }, 
        minute: { $toInt: { $arrayElemAt: [ { $split: [ "$from", ":" ] }, 1 ] } }
    }
}

Compared to

{
    $dateFromParts : {
        ...,
        hour: "$from.hour", 
        minute: "$from.minute"
    }
}

Another approach is to store real Date, e.g. 0000-01-01T13:00:00 or any other arbitrary day value. When you use such values, simply ignore the date part.

Or you store number of minutes (0..1'440) or seconds (0..86'400) from midnight. However, such numbers are not user-friendly to read.

  • Related