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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s