Querying MongoDB ObjectId by Date range

I had a situation where I wanted to query a collection in the production environment for a specific day, but the surprise for me was that the collection has no CreatedAt field in it in the first place :), so I had to rely on the ObjectId of the document. Searching around for a while I found this answer by kate, so I wanted to share it with all of you, & even shared it as an answer on another StackOverflow question.

And here it goes, let’s assume we want to query for April 4th 2015, we can do it in the terminal like this:

> var objIdMin = ObjectId(Math.floor((new Date('2015/4/4'))/1000).toString(16) + "0000000000000000")
> var objIdMax = ObjectId(Math.floor((new Date('2015/4/5'))/1000).toString(16) + "0000000000000000")
> db.collection.find({_id:{$gt: objIdMin, $lt: objIdMax}}).pretty()
Advertisements