0

How do you query time based queries from the ObjectID.timestamp()?

db.myCollectin.findOne()._id.getTimestamp()

I've tried

Date date = new Date();
BasicDBObject query = new BasicDBObject("timestamp", new BasicDBObject("$lt", date);
myCollection.findOne(query);

Problem:

Doesnt work

stackoverflow
  • 18,348
  • 50
  • 129
  • 196

1 Answers1

0

It doesn't work because your query looks for a field called timestamp which naturally doesn't exist.

You could do something like the shell query below, but be aware that Mongo will evaluate the JavaScript for every document in your collection - without using indices. I would recommend storing the date in a field on the documents if you need to query it regularly.

db.myCollection.find({$where: "this._id.getTimestamp() < ISODate('2015-03-04T21:18:21.419Z')"})
Martin
  • 5,119
  • 3
  • 18
  • 16
  • As pointed out in the answer to the question this [duplicates](http://stackoverflow.com/questions/8749971/can-i-query-mongodb-objectid-by-date) there is a much more efficient way to do this than by javascript evaluation which will of course use an index. – Neil Lunn Mar 05 '15 at 00:17