Skip to content

Commit 84cd241

Browse files
author
fso
committed
Add cursor support
1 parent 4d8fb95 commit 84cd241

File tree

1 file changed

+29
-2
lines changed

1 file changed

+29
-2
lines changed

src/Jenssegers/Mongodb/Query/Builder.php

+29-2
Original file line numberDiff line numberDiff line change
@@ -8,14 +8,20 @@
88
use Illuminate\Database\Query\Expression;
99
use Illuminate\Support\Arr;
1010
use Illuminate\Support\Collection;
11+
use Illuminate\Support\LazyCollection;
1112
use Illuminate\Support\Str;
1213
use Jenssegers\Mongodb\Connection;
1314
use MongoCollection;
1415
use MongoDB\BSON\Binary;
1516
use MongoDB\BSON\ObjectID;
1617
use MongoDB\BSON\Regex;
1718
use MongoDB\BSON\UTCDateTime;
19+
use RuntimeException;
1820

21+
/**
22+
* Class Builder
23+
* @package Jenssegers\Mongodb\Query
24+
*/
1925
class Builder extends BaseBuilder
2026
{
2127
/**
@@ -209,12 +215,25 @@ public function get($columns = [])
209215
return $this->getFresh($columns);
210216
}
211217

218+
/**
219+
* @inheritdoc
220+
*/
221+
public function cursor($columns = [])
222+
{
223+
$result = $this->getFresh($columns, true);
224+
if ($result instanceof LazyCollection) {
225+
return $result;
226+
}
227+
throw new RuntimeException("Query not compatible with cursor");
228+
}
229+
212230
/**
213231
* Execute the query as a fresh "select" statement.
214232
* @param array $columns
215-
* @return array|static[]|Collection
233+
* @param bool $returnLazy
234+
* @return array|static[]|Collection|LazyCollection
216235
*/
217-
public function getFresh($columns = [])
236+
public function getFresh($columns = [], $returnLazy = false)
218237
{
219238
// If no columns have been specified for the select statement, we will set them
220239
// here to either the passed columns, or the standard default of retrieving
@@ -402,6 +421,14 @@ public function getFresh($columns = [])
402421
// Execute query and get MongoCursor
403422
$cursor = $this->collection->find($wheres, $options);
404423

424+
if ($returnLazy) {
425+
return LazyCollection::make(function () use ($cursor) {
426+
foreach ($cursor as $item) {
427+
yield $item;
428+
}
429+
});
430+
}
431+
405432
// Return results as an array with numeric keys
406433
$results = iterator_to_array($cursor, false);
407434
return $this->useCollections ? new Collection($results) : $results;

0 commit comments

Comments
 (0)