Steven Carlson Steven Carlson - 7 months ago 26
Perl Question

Read MongoDB array into perl and walk data

I am trying to capture an array from my MongoDB database into my Perl script and read each element. This is something that I thought would be simple, but for some dumb reason it is kicking my rearend.

My MongoDB Document (in part)

"members" : [
"5713b2d46d210e51836de591",
"me",
"you",
"him",
"her"
],


Perl code

$document = $database -> get_collection('my_collection')->find_one({_id => $oid});
@members = $document->{'members'};
print Dumper @members;

foreach $member (@members)
{
print "member = $member\n";
}
exit;


Output I am getting:


$VAR1 = [

'5713b2d46d210e51836de591',

'me',

'you',

'him',

'her'

];

member = ARRAY(0x47fa398)


Looking at the last line I see that I am being passed a reference to the array instead of the values. So I tried accessing via $member[0] or $member[1] but that just returns the same ARRAY(0x*****).

PLEASE HELP, I am sure it is something stupid.

Thanks!

Steven

Answer

I'm not familiar with Mongo, but looking at the output, your @members array has one element - an array ref (as you suspected). Since Mongo is returning an arrayref, you're best to store that in a scalar and access it like so;

my $members = $document->{'members'};
print "second item returned is: ", $members->[1];
print "The complete contents:\n";
for my $item ( @$members )  {
    print "  ", $item;
}
Comments