I have searched for the answer without any results. I need to check if a Collection exists in my mongodatbase using MongoDB\Driver in PHP 7.1.6. Does anyone know how to do it? thanks.
5 Answers
I have done this method to verify if there exist a collection must pass the name, you will return 0 if it does not exist and 1 if it exists
public function verifyCollection($name){
$bd = $this->conexion->mongo();
$data = $bd->listCollections([
'filter' => [
'name' => $name,
],
]);
$exist = 0;
foreach ($data as $collectionInfo) {
$exist = 1;
}
return $exist;
}
Comments
Use db.getCollectionNames() and then test for existence of the collection you seek with indexOf() e.g.
idx = db.getCollectionNames().indexOf("myColl");
If idx = -1, then myColl does NOT exist. The equiv in perl would be
my @collections = $database->collection_names;
Then you can use smartmatch or grep or whatever you like to scan the collections list.
Comments
You can use listCollections() just remember it returns an object and not an array.
In the below code $collectionNames is an array of just the names.
$collections = $database->listCollections();
$collectionNames = [];
foreach ($collections as $collection) {
$collectionNames[] = $collection->getName();
}
Then check it like this:
$exists = in_array('some_collection', $collectionNames);
Comments
This worked for me. Basically you use listCollections() function, but it was not easy to figure out how to use it correctly in php-extension (thanks to @John56 for his answer in this thread). $manager is MongoDB\Driver\Manager class. Hope it helps you to save some time :)
$command = new Command(['listCollections' => 1, 'filter' => ['name' => 'collection-name']]);
$result = $manager->executeCommand('db-name', $command)->toArray();
if (false == empty($result) { whatever ...}