sortingdatemongodbgranularity

granularity in a MongoDB date sort?


Is it possible to sort MongoDB's date values with a granularity?

I'd like to order my results by date, but I don't care about the hour/minute/second data. I'd prefer not to have to store an additional parameter like '20101215'.


Solution

  • The short answer to your question is "No". It's not possible without storing another field. Even if it were possible you wouldn't want to b/c when sorting in Mongo you really need to index the fields you are sorting by, otherwise the db will need to scan every document in the db to do the sort. So if you were to do what you are suggesting you would also need to index on the partial date field which is also not possible in mongo.

    I think the best approach would be to store 2 fields, one for the year/month/day and another for the hour/min/secs. Then you'll have more flexibility with sorting and indexing. It's not as clean or ideal as you'd probably like, but that's the only option with the db.

    The other option would be to refine the order in your application after the results come back.