3

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 5

4

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;
 } 
Sign up to request clarification or add additional context in comments.

Comments

3

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

1

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

0

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 ...}

Comments

-1

First create your mongo object here $mongodb_object then

$collections = $mongodb_object->getCollectionNames();

The collections variable contains all the collection names as array Return array example is given below

[0] => collection_name1
[1] => collection_name2
[2] => collection_name3

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.