Search code examples
mongodbnode-mongodb-native

Check for opening hours- MongoDB


Can I find whether library is open or closed now without changing following schemas:

"openhours" : {
                    "sun" : {
                        "day" : "Sun",
                        "active" : true,
                        "open" : "01:00",
                        "close" : "00:05"
                    },
                    "mon" : {
                        "day" : "Mon",
                        "active" : false,
                        "open" : "00:00",
                        "close" : "00:00"
                    },
                    "tue" : {
                        "day" : "Tue",
                        "active" : false,
                        "open" : "00:00",
                        "close" : "00:00"
                    },
                   ...
                    "sat" : {
                        "day" : "Sat",
                        "active" : false,
                        "open" : "00:00",
                        "close" : "00:00"
                    }
}

I did a lot of research and can't find any solution when time is stored as HH:MM format in documents.

Any help is appreciated?


Solution

  • Even though times are stored in "HH:MM" format, it seems that you can still make sensible queries (thanks to zero padding you have there, lexicographical order of those time strings is the same as time order).

    Here's some pseudo-code for you:

    var date = new Date();
    var hhmm = date.getHHMM(); // '20:46'
    var dayname = date.getDayName(); // 'thu'
    
    db.library.find({"openhours.#{dayname}.open": {'$lt': hhmm}, "openhours.#{dayname}.close": {'$gt': hhmm}});