Steven Carlson Steven Carlson - 1 year ago 51
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" : [

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";

Output I am getting:

$VAR1 = [







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.




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;