You are here

public function Query::execute in MongoDB 8

Execute the query.

Return value

int|array Returns an integer for count queries or an array of ids. The values of the array are always entity ids. The keys will be revision ids if the entity supports revision and entity ids if not.

Overrides QueryInterface::execute

File

src/Entity/Query.php, line 27
Contains Drupal\mongodb\Entity\ContentEntityStorage.

Class

Query

Namespace

Drupal\mongodb\Entity

Code

public function execute() {
  try {
    $find = $this->condition
      ->compile($this->entityType);
  } catch (QueryException $e) {
    return array();
  }
  $prefix = $this->allRevisions ? 'entity_revision' : 'entity';
  $fields = [
    '_id' => 1,
    'entity_id' => 1,
    'revision_id' => 1,
  ];
  $cursor = $this->mongo
    ->get($prefix . '.' . $this->entityType
    ->id())
    ->find($find, $fields);
  if ($this->count) {
    return $cursor
      ->count();
  }
  if ($this->sort) {
    foreach ($this->sort as $sort) {
      $mongo_sort['values.' . $sort['field']] = strtoupper($sort['direction']) == 'ASC' ? 1 : -1;
    }
    file_put_contents('/tmp/sort', json_encode($mongo_sort) . "\n", FILE_APPEND);
    $cursor
      ->sort($mongo_sort);
  }
  if ($this->range) {
    $cursor
      ->skip($this->range['start']);
    $cursor
      ->limit($this->range['length']);
  }
  $return = array();
  foreach ($cursor as $id => $record) {
    $key = isset($record['revision_id']) ? $record['revision_id'] : $record['_id'];
    $value = isset($record['entity_id']) ? $record['entity_id'] : $record['_id'];
    $return[$key] = $value;
  }
  return $return;
}