开发者

What is the best way to format a date in JSON for Mongo DB storage

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开发者_如何学Python 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!


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"}


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.


I don't like relying on mongo Date objects. I think Mongo is slower with 'date' objects than it is with other data types (such as integers).

I tend to use integers (if you need timezone, have a tz field too, then you have localized time):

document = {:some_timestamp => Time.now.to_i}
@collection.find({'some_timestamp' => {'$gte' => Time.now.to_i}})

Sometimes I just use the timestamp built into the BSON::ObjectId's:

id = BSON::ObjectId.from_time(Time.now)
@collection.find({'_id' => {'$lte' => id}})
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜