From the MongoDB console, I can:
> db.log.insert({ dt : new Date })
> db.log.find().sort({ $natural : -1 }).limit(1)
{ "_id" : ObjectId("50caae2cadd0e471af0b3941"), "dt" : ISODate("2012-12-14T04:42:20.560Z") }
How can I do the same from the Perl MongoDB driver?
Background
I am using MongoDB with a capped collection for logging. I understand that the ObjectID contains a timestamp, but displaying it and querying it is not simple. I would therefore like to add a server-based timestamp to each entry, but have been unable to figure out how to pass literal commands via the Perl driver.
The Perl MongoDB Driver uses DateTime objects to store Dates, and returns DateTime object back to you if you read dates from the database.
If you execute it, it prints something like
You should also read the DateTime Documentation to understand what you can do with it: http://search.cpan.org/perldoc?DateTime
On the Connection startup you can also set which Date object you want.
http://search.cpan.org/perldoc?MongoDB::Connection#dt_type
If you set it to DateTime::Tiny for example it will be faster. But you should first understand the difference between DateTime and DateTime::Tiny. Read the Documentation of booth and decide in which case the one or the other is better.
The example above creates the client time. If you want the time from the server instead of your client, because client/server are not the same. You can do two things.
At first, create a JavaScript function that returns a Date object und evaluate the function on the server.
The second possibility. The default “_id” object from MongoDB already contains a timestamp when the object will be created. At least the documentation says it comes from the server, and i hope it really comes from the server and will not created by the driver. But if $entry is your MongoDB result you can get a DateTime object from it this way:
Example:
Output: