user1906825
user1906825

Reputation: 185

Is it possible to parse Queries in MongoDB to get more specific results?

I want to get time greater than 2:00 and less than 8:00 in my mongoDb. However, my data looks like this:

{"time": "4:35"}

The colon prevents me from making queries like "db.collection.find( { time: { $gt: 2, $lt: 8 } } )" Is there some way to query this? (Perhaps parse 4:35 into 435 without changing the inner data)

Upvotes: 0

Views: 128

Answers (2)

Philipp
Philipp

Reputation: 69703

Storing times as strings is a bad idea. Unfortunately MongoDB has no dedicated time-only data type, but there are two alternatives which are not as bad as using strings:

  1. use a BSON Date. When storing the year, month and day would be counter-productive, set all these to the same value (the start of the epoch, Jan 1st 1970, would be an option).
  2. use an integer, and have it represent the number of minutes or seconds since midnight. Do the conversion on the application-layer.

Upvotes: 0

Satheesh Kumar
Satheesh Kumar

Reputation: 156

if you just wanted to search for the time between 2 and 8 then you could probably try this:

db.collection.find( { time: { $gt: "2:00", $lt: "8:00" } } )

This is what i have done to test this. I have inserted few data to the collections and here is the the list:

db.time.find({},{"_id":0})
{ "mytime" : "4:35" }
{ "mytime" : "1:35" }
{ "mytime" : "6:35" }
{ "mytime" : "8:35" }
{ "mytime" : "10:35" }
{ "mytime" : "10:10" }

db.time.find( { mytime: { $gt: "2:00", $lt: "8:00" } }, {"_id":0} )
{ "mytime" : "4:35" }
{ "mytime" : "6:35" }

Upvotes: 1

Related Questions