Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find All Objects Created Before 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 would I get about finding all documents that were created before lets say February 10th 2014? Searched around but doesn't seem like this question comes up. Any help is appreciated! Thanks!

like image 366
Dustin Avatar asked Feb 25 '14 21:02

Dustin


People also ask

What is $GTE in MongoDB?

$gte selects the documents where the value of the field is greater than or equal to (i.e. >= ) a specified value (e.g. value .) For most data types, comparison operators only perform comparisons on fields where the BSON type matches the query value's type.

What is ISODate in MongoDB?

ISODate() is a helper function that's built into to MongoDB and wraps the native JavaScript Date object. When you use the ISODate() constructor from the Mongo shell, it actually returns a JavaScript Date object.

How to use find query in MongoDB?

To find documents that match a set of selection criteria, call find() with the <criteria> parameter. MongoDB provides various query operators to specify the criteria. For a list of the query operators, see Query Selectors.


1 Answers

You mean something like this?

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

Guess that you have to make the same as JoJo recommended:

  1. Convert a date to an ObjectId
  2. 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}})

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

like image 151
briba Avatar answered Oct 17 '22 17:10

briba