MongoDB cursor to hash in Perl

505 Views Asked by At

So, I'm retrieving some values from MongoDB. I now that find method returns a cursor, which lazy loads the query results. I want to have the cursor stored as a hash, but I can find any method. Of course, you can iterate over the cursor and fill the has by yourself, but I'm interested in a automated way. For example, in Python, you could do this: myList = list(col.find()) to get all the cursor items as a list.

Would it be possible doing something similar in Perl?

1

There are 1 best solutions below

0
simbabque On BEST ANSWER

When you call find, it returns a cursor object, which delegates iterator methods to a MongoDB::QueryResult. When you do a next on that thing, it returns one document at a time lazily. That document already is the full set of data. This might be a hash reference already (or an object, I don't know).

use Data::Dumper;
while (my $object = $cursor->next) {
    print Dumper $object;
}

If you want all of them at once, you can get a list with the all method, which you can then put into an array and use at your convenience. This will not load on demand.

my @objects = $cursor->all;