I'm using the Mongo shell to query my Mongo db. I want to use the timestamp contained in the ObjectID as part of my query and also as a column to extract into output. I have setup Mongo to create ObjectIDs on its own.
My problem is I can not find out how to work with the ObjectID to extract its timestamp.
Here are the queries I am trying to get working. The 'createdDate' field is a placeholder; not sure what the correct field is:
//Find everything created since 1/1/2011 db.myCollection.find({date: {$gt: new Date(2011,1,1)}}); //Find everything and return their createdDates db.myCollection.find({},{createdDate:1});
The _id field contains the date when the document was inserted into the collection. You can use the getTimestamp() method to extract the date from the ObjectId.
Making sure that all your applications create and update MongoDB timestamps is going to be the hardest part of this process; MongoDB has no automatic timestamp support, so every one of your applications is going to have to make sure they do one of two things when working with the database: write a createdAt field, or ...
Working of the timestamp in mongodb is simple, where when executed, the timestamp method will call the currentDate(), which will pick the current date and time of the system. This picked date and time will be stored in the collection, along with the other data values.
The function you need is this one, it's included for you already in the shell:
ObjectId.prototype.getTimestamp = function() { return new Date(parseInt(this.toString().slice(0,8), 16)*1000); }
Check out this section from the docs:
This unit test also demostrates the same:
> db.col.insert( { name: "Foo" } ); > var doc = db.col.findOne( { name: "Foo" } ); > var timestamp = doc._id.getTimestamp(); > print(timestamp); Wed Sep 07 2011 18:37:37 GMT+1000 (AUS Eastern Standard Time) > printjson(timestamp); ISODate("2011-09-07T08:37:37Z")
This question is helpful to understand of how to use the _id's embedded timestamp in query situations (refers to the Mongo Extended JSON documentation). This is how it's done:
col.find({..., '_id' : {'$lt' : {'$oid' : '50314b8e9bcf000000000000'}} })
finds documents created earlier than the one that's given by oid. Used together with natural sorting and limiting you can utilize BSON _ids to create Twitter-like API queries (give me the last OID you have and I'll provide twenty more)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With