MongoCollection::createIndex PHP Method

createIndex() public method

Creates an index on the given field(s), or does nothing if the index already exists
public createIndex ( array $keys, array $options = [] ) : array
$keys array Field or fields to use as index.
$options array [optional] This parameter is an associative array of the form array("optionname" => , ...).
return array Returns the database response.
    public function createIndex($keys, array $options = [])
    {
        if (is_string($keys)) {
            if (empty($keys)) {
                throw new MongoException('empty string passed as key field');
            }
            $keys = [$keys => 1];
        }
        if (is_object($keys)) {
            $keys = (array) $keys;
        }
        if (!is_array($keys) || !count($keys)) {
            throw new MongoException('index specification has no elements');
        }
        if (!isset($options['name'])) {
            $options['name'] = \MongoDB\generate_index_name($keys);
        }
        $indexes = iterator_to_array($this->collection->listIndexes());
        $indexCount = count($indexes);
        $collectionExists = true;
        $indexExists = false;
        // listIndexes returns 0 for non-existing collections while the legacy driver returns 1
        if ($indexCount === 0) {
            $collectionExists = false;
            $indexCount = 1;
        }
        foreach ($indexes as $index) {
            if ($index->getKey() === $keys || $index->getName() === $options['name']) {
                $indexExists = true;
                break;
            }
        }
        try {
            foreach (['w', 'wTimeoutMS', 'safe', 'timeout', 'wtimeout'] as $invalidOption) {
                if (isset($options[$invalidOption])) {
                    unset($options[$invalidOption]);
                }
            }
            $this->collection->createIndex($keys, $options);
        } catch (\MongoDB\Driver\Exception\Exception $e) {
            throw ExceptionConverter::toLegacy($e, 'MongoResultException');
        }
        $result = ['createdCollectionAutomatically' => !$collectionExists, 'numIndexesBefore' => $indexCount, 'numIndexesAfter' => $indexCount, 'note' => 'all indexes already exist', 'ok' => 1.0];
        if (!$indexExists) {
            $result['numIndexesAfter']++;
            unset($result['note']);
        }
        return $result;
    }

Usage Example

 /**
  * Note that we use TTL Collections to have the Mongo deamon automatically clean
  * expired entries.
  *
  * @link http://docs.mongodb.org/manual/tutorial/expire-data/
  * @param array $options
  */
 public function __construct(array $options = array())
 {
     if (!extension_loaded('mongo')) {
         Zend_Cache::throwException('The MongoDB extension must be loaded for using this backend !');
     }
     parent::__construct($options);
     // Merge the options passed in; overriding any default options
     $this->_options = array_merge($this->_options, $options);
     $conn = new \MongoClient($this->_getServerConnectionUrl());
     $this->_database = $conn->{$this->_options['dbname']};
     $this->_collection = $this->_database->selectCollection($this->_options['collection']);
     $this->_collection->createIndex(array('tags' => 1), array('background' => true));
     $this->_collection->createIndex(array('expires_at' => 1), array('background' => true, 'expireAfterSeconds' => 0));
 }
All Usage Examples Of MongoCollection::createIndex