Sometimes you need to truncate a large collection on MongoDB ( mine is 1.6 billion documents ) on an unindexed field, such as a Mongoid field called created_at. ( OK, TTL collections exists to solve this, but this is a transient solution before we can reindex those 1.6 B documents).

This command: db.collection.remove({created_at : {$lt : ISODate("2012-10-09") }}) will trigger a full table scan which can take hours to run before any actual document is deleted. .

Object Id to the rescue!!!

MongoDB´s ObjectID comes with timestamp for the Object´s creation time inside for free (http://docs.mongodb.org/manual/core/object-id/)

So, with a little help from stackoverflow and  and Kristina Chodorow (http://www.kchodorow.com/blog/2011/12/20/querying-for-timestamps-using-objectids/) , I created a fake ObjectID from a specified date and then removed over the collection based on the _id field, which is indexed by default, so I remove every _id created before this date!

> time = new ISODate("2012-12-09")
> ms = time.getTime()
> sec = Math.floor(ms/1000)
> hex = sec.toString(16)
> id_string = hex + "0000000000000000"
> my_id = ObjectId(id_string)
>
> db.my_collection.remove( { _id: { $lt: my_id } } )


A cool and indexed query, much faster than the other option!