jv-y9q
Last Updated: February 25, 2016
·
3.655K
· abh1nv

Converting a Date to a Mongo ObjectId

If you're looking to find documents in a collection by insertion date but don't have a created_time field, fear not.

DateTime minDate = new DateTime().minusDays(2);
Long timestamp = minDate.getMillis() / 1000L;
String oidString = Long.toHexString(l) + "0000000000000000";

And now you can run a query like so:

ObjectId id = new ObjectId(oidString);
DBObject query = new BasicDBObject("_id",
                     new BasicDBObject("$gt", id));