================================ MongoDBCollection::createIndex() ================================ .. default-domain:: mongodb .. contents:: On this page :local: :backlinks: none :depth: 1 :class: singlecol Definition ---------- .. phpmethod:: MongoDB\\Collection::createIndex($key, $options) Create an index for the collection. .. code-block:: php function createIndex($key, array $options = []): string ``createIndex()`` accepts the following parameters: .. include:: /includes/apiargs/MongoDBCollection-method-createIndex-param.rst The ``$options`` parameter accepts all index options that your MongoDB version supports. MongoDB 3.2 includes the following options: .. include:: /includes/apiargs/MongoDBCollection-method-createIndex-option.rst For a full list of the supported index creation options, refer to the :manual:`createIndexes ` command reference in the MongoDB manual. Output ------ Returns the name of the created index as a string. Examples -------- Create a Compound Index ~~~~~~~~~~~~~~~~~~~~~~~ The following operation creates a :manual:`compound index ` on the ``borough`` and ``cuisine`` fields in the ``restaurants`` collection. .. code-block:: php selectCollection('example','restaurants'); $keys = ['borough' => 1, 'cuisine' => 1]; $indexString = $collection->createIndex($keys, ['name' => 'compound']); var_dump($indexString); The output would resemble the following: .. code-block:: none string(8) "compound" Create a Partial Index ~~~~~~~~~~~~~~~~~~~~~~ The following operation adds a :manual:`partial index ` on the ``borough`` field in the ``restaurants`` collection in the ``example`` database. The partial index indexes only fields where the ``borough`` field exists. .. code-block:: php selectCollection('example','restaurants'); $indexString = $collection->createIndex( ['borough' => 1], ['partialFilterExpression'=> ['borough'=> ['$exists'=>true] ]]); var_dump($indexString); The output would resemble:: string(9) "borough_1" .. seealso:: - :phpmethod:`MongoDB\\Collection::createIndexes` - :doc:`/tutorial/indexes` - :manual:`createIndexes ` command reference in the MongoDB manual - :manual:`Index documentation `