Alfons
Alfons

Reputation: 331

Perl and MongoDB... find and take results

Ok.. I'd like take "name" and "id" value...but how?! :)

my $results = $collection->find( { })->fields( { name => 1, _id => 1 } );
while (my $doc = $results->next){
  foreach my $key (keys %$doc){
    my $name = $doc->{$key};
    ...
    print "name: $name\n";
    print "id: $id\n";
  }
}

Upvotes: 1

Views: 122

Answers (1)

Hannibal
Hannibal

Reputation: 445

Simply accessing to attributes you need inside each document :) Example using a cursor iterator:

my $cursor = $collection->find({})->fields({ 
   name => 1, 
   _id => 1 
});
while (my $doc = $cursor->next){
    say "name: $doc->{name}" ;
    say " _id: $doc->{_id}" ;
}

or slurping all results at once:

map {
    say "name: $_->{name}" ;
    say " _id: $_->{_id}" ;
} $cursor->all ;

Upvotes: 2

Related Questions