tags:

views:

266

answers:

2

I have a date with a time. I'm using ruby, but the language shouldn't matter.

d = "2010-04-01 13:00:00"

What is the best way to format this date for Mongo DB? By 'best' I mean, is there a certain format I could use where Mongo would recognize it as a date and might give me more-advanced filtering optons?

ie: If formatted correctly, could I ask Mongo to return all records whose month is '04'?

Thanks!

+3  A: 

You don't need to format dates at all; dates are a supported data type. Each client driver should support dates through their standard date type, including the ruby one.

For advanced queries like your example, you can use a javascript expression for the find specifier:

{"$where": "this.date.getMonth() == 3"}
Coady
Just to clarify, since it's far from obvious, the reason it says 3 instead of 4 in the code example above is that for some mysterious reason the months go from 0 to 11 in JavaScript.
Theo
+1  A: 

In ruby you should use a Time instance, which will get stored as the BSON datetime type. You could use a $where clause like Coady mentions, but will be better to do a range query with $lt and $gt - less overhead and can leverage an index.

mdirolf