Skip to content

Commit 2dcfa5b

Browse files
committed
Add getCollection function and little improvements
Add getCollection function and little improvements
1 parent bf1e25a commit 2dcfa5b

File tree

2 files changed

+28
-11
lines changed

2 files changed

+28
-11
lines changed

src/Jenssegers/Mongodb/Schema/Builder.php

Lines changed: 27 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -33,21 +33,20 @@ public function hasColumns($table, array $columns)
3333

3434
/**
3535
* Determine if the given collection exists.
36-
* @param string $collection
37-
* @param bool $collection_info
38-
* @return bool|\MongoDB\Model\CollectionInfo
36+
* @param string $name
37+
* @return bool
3938
*/
40-
public function hasCollection($collection, $collection_info = false)
39+
public function hasCollection($name)
4140
{
4241
$db = $this->connection->getMongoDB();
4342

44-
foreach ($db->listCollections() as $collectionFromMongo) {
45-
if ($collectionFromMongo->getName() == $collection) {
46-
return $collection_info ? $collectionFromMongo : true;
47-
}
48-
}
43+
$collections = $db->listCollections([
44+
'filter' => [
45+
'name' => $name,
46+
],
47+
]);
4948

50-
return false;
49+
return $collections->count() ? true : false;
5150
}
5251

5352
/**
@@ -135,6 +134,24 @@ protected function createBlueprint($collection, Closure $callback = null)
135134
return new Blueprint($this->connection, $collection);
136135
}
137136

137+
/**
138+
* Get collection.
139+
* @param string $name
140+
* @return bool|\MongoDB\Model\CollectionInfo
141+
*/
142+
public function getCollection($name)
143+
{
144+
$db = $this->connection->getMongoDB();
145+
146+
$collections = $db->listCollections([
147+
'filter' => [
148+
'name' => $name,
149+
],
150+
]);
151+
152+
return $collections->count() ? (($collections = iterator_to_array($collections) ) ? current($collections) : false) : false;
153+
}
154+
138155
/**
139156
* Get all of the collections names for the database.
140157
* @return array

tests/SchemaTest.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ public function testCreateWithOptions(): void
3535
$this->assertTrue(Schema::hasCollection('newcollection_two'));
3636
$this->assertTrue(Schema::hasTable('newcollection_two'));
3737

38-
$collection = Schema::hasCollection('newcollection_two', true);
38+
$collection = Schema::getCollection('newcollection_two');
3939
$this->assertTrue($collection['options']['capped']);
4040
$this->assertEquals(1024, $collection['options']['size']);
4141
}

0 commit comments

Comments
 (0)