You are here

public function Logger::ensureCollection in MongoDB 8.2

Ensure a collection exists in the logger database.

  • If it already existed, it will not lose any data.
  • If it gets created, it will be empty.

Parameters

string $name: The name of the collection.

Return value

\MongoDB\Collection The chosen collection, guaranteed to exist.

Throws

\MongoDB\Exception\InvalidArgumentException

\MongoDB\Exception\UnsupportedException

\MongoDB\Driver\Exception\RuntimeException

1 call to Logger::ensureCollection()
Logger::ensureCappedCollection in modules/mongodb_watchdog/src/Logger.php
Ensure a collection is capped with the proper size.

File

modules/mongodb_watchdog/src/Logger.php, line 496

Class

Logger
Class Logger is a PSR/3 Logger using a MongoDB data store.

Namespace

Drupal\mongodb_watchdog

Code

public function ensureCollection(string $name) : Collection {
  $collection = $this->database
    ->selectCollection($name);
  $info = current(iterator_to_array($this->database
    ->listCollections([
    'filter' => [
      'name' => $name,
    ],
  ])));

  // If the collection doesn't exist, create it, ensuring later operations are
  // actually run after the server writes:
  // https://docs.mongodb.com/manual/reference/write-concern/#acknowledgment-behavior
  if ($info === FALSE) {
    $res = $collection
      ->insertOne([
      '_id' => 'dummy',
      [
        'writeConcern' => [
          'w' => WriteConcern::MAJORITY,
          'j' => TRUE,
        ],
      ],
    ]);

    // With these options, all writes should be acknowledged.
    if (!$res
      ->isAcknowledged()) {
      throw new RuntimeException("Failed inserting document during ensureCollection");
    }
    $collection
      ->deleteMany([]);
  }
  return $collection;
}