You are here

public static function MongoDb::countCollection in MongoDB 8.2

Count items matching a selector in a collection.

This function used to be needed when:

  • library versions below and above 1.4.0 were supported, as in 8.x-2.0. With the minimum version now being 1.5.0, the Collection::count() method is no longer needed and is deprecated.
  • MongoDB PHPLIB-376 was not yet fixed and needed the try/catch around Collection::countDocuments().

Since both issues have been resolved, this method is only used for compatibility and will be deprecated after the Drupal 9.0 release. It is not marked as deprecated to avoid a Drupal 9 compatibility check.

Parameters

\MongoDB\Collection $collection: The collection for which to count items.

array $selector: The collection selector.

Return value

int The number of elements matching the selector in the collection.

See also

https://jira.mongodb.org/browse/PHPLIB-376

1 call to MongoDb::countCollection()
MongoDbTest::testCountCollection in modules/mongodb/tests/src/Kernel/MongoDbTest.php
@covers ::countCollection

File

modules/mongodb/src/MongoDb.php, line 92

Class

MongoDb
Class MongoDb contains constants usable by all modules using the driver.

Namespace

Drupal\mongodb

Code

public static function countCollection(Collection $collection, array $selector = []) : int {
  try {
    $count = $collection
      ->countDocuments($selector);
  } catch (UnexpectedValueException $e) {
    $count = 0;
  }
  return $count;
}