Perl Mongo find object Id Perl Mongo find object Id mongodb mongodb

Perl Mongo find object Id


the find methods returns a Cursor object for iterating through. If you only want one record use the find_one method which returns a value.

my $client = MongoDB::MongoClient->new;my $db = $client->get_database( 'myDatabase' );my $id_find = $db->get_collection('mycollection')->find_one({_id => MongoDB::OID->new(value => "5106c7703abc120a04070b34")});print Dumper $id_find;


The answer to this has changed. MongoDB::OID has been deprecated, replaced by BSON::OID, which does not have a method that allows you to pass in the 24-byte hex string that you have. Here's what you have to do these days:

my $id = "5c7463277fc2198b64654feb";my $oid = BSON::OID->new(oid => pack('H24', $id));my $result = $db->get_collection('mycollection')->find_id($oid);

pack creates a 12-byte binary sequence from the 24-bytes of hexadecimal data you have in $id. This is what BSON::OID is expecting, and then the perl driver constructs the correct filter for you in the background.