Navigation

MongoDB\Database::listCollections()

Definition

MongoDB\Database::listCollections

Returns information for all collections in this database.

function listCollections(array $options = []): MongoDB\Model\CollectionInfoIterator

This method has the following parameters:

Parameter Type Description
$options array Optional. An array specifying the desired options.

The $options parameter supports the following options:

Option Type Description
filter array|object

Optional. A query expression to filter the list of collections.

You can specify a query expression on the collection name and options.

maxTimeMS integer Optional. The cumulative time limit in milliseconds for processing operations on the cursor. MongoDB aborts the operation at the earliest following interrupt point.

Return Values

A traversable MongoDB\Model\CollectionInfoIterator, which contains a MongoDB\Model\CollectionInfo object for each collection in the database.

Example

The following example lists all of the collections in the test database:

<?php

$database = (new MongoDB\Client)->test;

foreach ($database->listCollections() as $collectionInfo) {
    var_dump($collectionInfo);
}

The output would then resemble:

object(MongoDB\Model\CollectionInfo)#3 (2) {
  ["name"]=>
  string(11) "restaurants"
  ["options"]=>
  array(0) {
  }
}
object(MongoDB\Model\CollectionInfo)#3 (2) {
  ["name"]=>
  string(5) "users"
  ["options"]=>
  array(0) {
  }
}
object(MongoDB\Model\CollectionInfo)#3 (2) {
  ["name"]=>
  string(6) "restos"
  ["options"]=>
  array(0) {
  }
}

The following example lists all collections whose name starts with "rest" in the test database:

<?php

$database = (new MongoDB\Client)->test;

$collections = $database->listCollections([
    'filter' => [
        'name' => new MongoDB\BSON\Regex('^rest.*'),
    ],
]);

foreach ($collections as $collectionInfo) {
    var_dump($collectionInfo);
}

The output would then resemble:

object(MongoDB\Model\CollectionInfo)#3 (2) {
  ["name"]=>
  string(11) "restaurants"
  ["options"]=>
  array(0) {
  }
}
object(MongoDB\Model\CollectionInfo)#3 (2) {
  ["name"]=>
  string(6) "restos"
  ["options"]=>
  array(0) {
  }
}

See Also