Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get returned data from mongoDB in Perl?

Tags:

mongodb

perl

I read http://api.mongodb.org/perl/current/MongoDB/Examples.html and seems to be only documentation from mongoDB on Perl. How do I get my query result from mongoDB in perl. Let us say into Hash. I have successfully made connection to the db so far. I managed to do inserts into collections. Now how do I issue select query and get its returned data into hash or something similar?

Update:

Example of my data
{
 "_id" : ObjectId("asdhgajsdghajgh"),
 "country" : "USA"
 "city" : "Boston"
}

{
 "_id" : ObjectId("asdhgajsdghajgh"),
 "country" : "USA"
 "city" : "Seattle"
}

{
 "_id" : ObjectId("asdhgajsdghajgh"),
 "country" : "Canada"
 "city" : "Calgary"
}

My code

my $cursor = $my_collection
    ->find({ country => 1 }) 
    ;
while (my $row = $cursor->next) {
    print "$row\n";
}

This code is not resulting any output. I want to basically iterate through the entire collection and read document by document. Not sure what I am doing wrong. I used the code above. I changed $cur->next to $cursor->next I am guessing it was a typo. I appreciate all the answers so far.

like image 770
DoodleKana Avatar asked Jan 15 '13 23:01

DoodleKana


1 Answers

That's not the official documentation. Head right to the CPAN:

  • MongoDB::Tutorial
  • MongoDB::Examples

Iterating results is pretty similar to the DBI way:

use Data::Printer;
use MongoDB;

# no query is performed on initialization!
my $cursor = $collection
    ->find({ active => 1, country => 'Canada' }) # filter "active" records from Canada
    ->sort({ stamp => -1 }) # order by "stamp" attribute, desc.
    ->limit(1000);          # first 1000 records

# query & iterate
while (my $row = $cur->next) {
    # it is 'p', from Data::Printer!
    p $row;
}
like image 99
creaktive Avatar answered Nov 13 '22 03:11

creaktive