MARTIMM / raku-mongodb-driver

MongoDB driver for Raku
Artistic License 2.0
18 stars 8 forks source link

$collection.find could return an Iterable #22

Closed szabgab closed 6 years ago

szabgab commented 7 years ago

Like this:

for $collection.find -> BSON::Document $d {
}

Which would require less code by the user.

lizmat commented 7 years ago
method iterator() {
   class :: does Iterator {
       has $.cursor
       method pull-one() {
           if $!cursor.fetch -> $d {
                $d
           }
           else {
                IterationEnd
           }
       }
   }.new(cursor => self)
}

This method defines an anonymous class that does the Iterator role, and instantiates an object of it using the Cursor object itself. Iterator classes must provide at least a "pull-one" method that should either return the next element, or the special IterationEnd value.

More documentation about the Iterator role can be found at https://docs.perl6.org/type/Iterator .

https://perl6.party/post/Perl-6-Seqs-Drugs-and-Rock-n-Roll and https://perl6.party/post/Perl-6-Seqs-Drugs-and-Rock-n-Roll--Part-2 contain a very nice introduction to this as well.

MARTIMM commented 7 years ago

Hi Gabor,

This is possible. The find method returns a Cursor object which can be used to get the documents. This can be done in two ways; using the Cursor object as an iterator or just use fetch in a while loop. In test 't/450-find.t' there is a sub 'check-document' at the end which does just that.

Regards, Marcel

On July 8, 2017 16:43:35 Gabor Szabo notifications@github.com wrote:

Like this:

for $collection.find -> BSON::Document $d {
}

Which would require less code by the user.

-- You are receiving this because you are subscribed to this thread. Reply to this email directly or view it on GitHub: https://github.com/MARTIMM/mongo-perl6-driver/issues/22