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.
That's not the official documentation. Head right to the CPAN:
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With