Re: Creating a MongoDB::OID object from the _id field returned by a Perl find_one query

95 views
Skip to first unread message

Stephen Steneker

unread,
Oct 13, 2012, 2:29:35 AM10/13/12
to mongod...@googlegroups.com

I want to extract the timestamp from a MongoDB document's _id field in Perl.  I've been trying to create a MongoDB::OID object from the _id string returned by a find_one, but it complains about illegal hexadecimal digits.  What am I doing wrong?

my $object = $inventoryColl->find_one();
my $objID = MongoDB::OID->new(value => $object->{_id});
my $time = $objID->get_time;   # this line produces an error
my $date = DateTime->from_epoch(epoch => $objID->get_time);  # also produces error

Hi,

Assuming your _id is an ObjectID and not a custom string value, it should already returned as a MongoDB::OID.

So this should work:

my $object = $inventoryColl->find_one();
my $objID = $object->{'_id'};
my $date = DateTime->from_epoch(epoch => $objID->get_time);
print "date: $date\n";

If you're not sure what is being returned, Data::Dumper will show you the contents of a variable without stringifying:

Cheers,
Stephen

Steven Hirschorn

unread,
Oct 15, 2012, 12:26:55 PM10/15/12
to mongod...@googlegroups.com
Thanks Stephen,

Turns out the particular collection I was looking at had a custom _id field.  When I tried against a db with a Mongo-created _id field everything worked.  Thanks for your response.#
Reply all
Reply to author
Forward
0 new messages