rit's ramblings
August 9, 2009
Quick MongoDB Date range Querying

I was playing for a bit with Mongo’s querying today, as I’m porting Sluggy.com from MySQL to MongoDB.  One thing I couldn’t figure out immediately was “active news stories”.  News Stories have an archived boolean (true means the article is no longer active) and a date range - start_date and end_date so Articles can be queued up (and off) early.

MongoDB doesn’t yet have an “or” clause, although the mailing list indicates it’s something they’ll be adding.  So you need to start off with your base query to get your head, and do a $where to filter out the tail. $where clauses in mongo are Javascript code.

The solution is:

    news = NewsStory.all({
        'archived': False,
        'start_date': {'$lte': datetime.datetime.today()}
    }).where('this.end_date == null || this.end_date >= new Date()')