Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle date stored as string in Mongodb?

So I have this field called task_time stored as string in Mongodb in 'YYYY-MM-DD' format (eg. '2012-12-21').

Now I need to query this collection to get the data whose task_time is within a given time interval.

The time interval is given as a pair of strings that represent start time and end time in 'YYYY-MM-DD hh:mm:ss' format (eg. '2015-12-21 16:00:00').

Is there any way to do this directly in Mongo query without bringing this task to my javascript code?

like image 824
delsin Avatar asked Jan 05 '16 08:01

delsin


People also ask

Can I store date as string in MongoDB?

MongoDB will treat them as they are - string data type. And, the string comparison rules will apply. You can safely store dates as strings and query on them as long as they are properly formatted for date, i.e., “YYYY-MM-ddTHH:mm:ss”.

How should dates be stored in MongoDB?

Internally, Date objects are stored as a signed 64-bit integer representing the number of milliseconds since the Unix epoch (Jan 1, 1970). Not all database operations and drivers support the full 64-bit range. You may safely work with dates with years within the inclusive range 0 through 9999 .

How do I query a date in MongoDB?

We can use date () command to get a date as a string in a query without the new keyword or MongoDB shell.

How do you change a field from a string to a date MongoDB?

The $toDate Operator The $toDate aggregation pipeline operator converts a value to a date. The value can be any type that that can be converted to a date, which is basically numbers, strings, and objectIds. See Mongo $toDate for more information and examples.


1 Answers

As I know $gte and $lt can work with strings too. The same in mongoose after this issue

items.find({
    task_time: {
        $gte: "2015-12-21 12:00:00",
        $lt: "2015-12-21 16:00:00" 
    }
})
like image 165
Manasov Daniel Avatar answered Sep 22 '22 11:09

Manasov Daniel