Mongo - find all objects created before the specified date

Mongo has a nice feature that tells you when a document was created.

ObjectId("53027f0adb97425bbd0cce39").getTimestamp() = ISODate("2014-02-17T21:28:42Z")

How can I find all documents that were created before February 10, 2014? I searched around, but it seems that this question does not arise. Any help is appreciated! Thank!

+3
source share
1 answer

Do you mean something like this?

db.YOUR_COLLECTION.find({YOUR_DATE_FIELD: { "$lt": ISODate("2014-02-10") }})

Guess what you should do the same as JoJo recommended:

  • Convert Date to ObjectId
  • Filter ID using $ lt and returned ObjectId

Using pymongo, you can do something like this:

gen_time = datetime.datetime(2014, 2, 10)
dummy_id = ObjectId.from_datetime(gen_time)
result   = collection.find({"_id": {"$lt": dummy_id}})

Link: http://api.mongodb.org/python/1.7/api/pymongo/objectid.html

+4
source

All Articles