0

I'm aware that the Mongo "ObjectId" has the method "getTimestamp()" , which works like

ObjectId("507f191e810c19729de860ea").getTimestamp()

And also I'm aware that it can be sorted based on built-in 'timestamp'

db.collection.find().sort({'timestamp': -1})

I know I can create a new field "created_time" in each document by converting ObjectId to created_time, then query based on this new field.

I've also read this post which converts the date range to ObjectId and then directly compare the ObjectId, but this method I'm worried about the other bytes which is not for time but for machine and process.

My question is, is there a way to directly query documents in a date range using Mongo built-in 'timestamp'? without extra field or extra effort.

something like below (but I tried below command and not working), which can directly query Mongo using its built-in timestamp.

db.collection.find({'timestamp':{$gt: new Date(ISODate("2015-08-14T14:00:00Z"))}})
Community
  • 1
  • 1
keypoint
  • 2,268
  • 4
  • 31
  • 59
  • 1
    There is no "built in timestamp"/default field or anything like that. There is only a default unless you tell the field to contain something else `ObjectId` implementation on the `_id` primary key ( or anywhere else you explicitly set an ObjectId created from time and not a pre-fed string ). From the post you reference, the preceeding bytes of the ObjectId are a truncated timestamp. So while you can use the method there or built in ones from some drivers, it is basically about constructing an ObjectId that represents a time and using that to query. But you cannot do this directly with a date. – Blakes Seven Aug 25 '15 at 23:20
  • Thanks Blakes, since no such a built-in variable 'timestamp', constructing ObjectId seems to be the way I should go. Thank you very much. – keypoint Aug 25 '15 at 23:53
  • 1
    Note that the "timestamp" component of an ObjectId is only granular to the "second" rather than the "millisecond". As such it is often not suitable for high capacity environments, where you should create a `Date` typed property instead. – Blakes Seven Aug 25 '15 at 23:59
  • For my project it doesn't have strict time precision to to second should be ok for me. Thanks a lot for the heads up :) – keypoint Aug 26 '15 at 00:07

0 Answers0