==================================
MongoDB\\Collection::createIndex()
==================================

.. default-domain:: mongodb

.. contents:: On this page
   :local:
   :backlinks: none
   :depth: 1
   :class: singlecol

Definition
----------

.. phpmethod:: MongoDB\Collection::createIndex()

   Create an index for the collection.

   .. code-block:: php

      function createIndex(
          array|object $key,
          array $options = []
      ): string

Parameters
----------

``$key`` : array|object
  Specifies the field or fields to index and the index order.

  For example, the following specifies a descending index on the ``username``
  field:

  .. code-block:: php

     [ 'username' => -1 ]

``$options`` : array
  An array specifying the desired options.

  The ``$options`` parameter accepts both index *and* command options. A
  non-exhaustive list of index options follows. For a complete list of index
  options, refer to the
  :manual:`createIndexes </reference/command/createIndexes>` command reference
  in the MongoDB manual.

  **Index Options** (non-exhaustive)

  .. list-table::
     :header-rows: 1
     :widths: 20 20 80

     * - collation
       - array|object
       - .. include:: /includes/extracts/collection-option-collation.rst

     * - expireAfterSeconds
       - integer
       - Creates a :manual:`TTL </core/index-ttl>` index.

     * - name
       - string
       - A name that uniquely identifies the index. By default, MongoDB creates
         index names based on the key.

     * - partialFilterExpression
       - array|object
       - Creates a :manual:`partial </core/index-partial>` index.

     * - sparse
       - boolean
       - Creates a :manual:`sparse </core/index-sparse>` index.

     * - unique
       - boolean
       - Creates a :manual:`unique </core/index-unique>` index.

  **Command Options**

  .. list-table::
     :header-rows: 1
     :widths: 20 20 80

     * - Name
       - Type
       - Description

     * - comment
       - mixed
       - .. include:: /includes/extracts/common-option-comment.rst

         .. include:: /includes/extracts/option-requires-4.4.rst

         .. versionadded:: 1.13

     * - commitQuorum
       - string|integer
       - Specifies how many data-bearing members of a replica set, including the
         primary, must complete the index builds successfully before the primary
         marks the indexes as ready.

         This option accepts the same values for the ``w`` field in a write
         concern plus ``"votingMembers"``, which indicates all voting
         data-bearing nodes.

         This is not supported for server versions prior to 4.4 and will result
         in an exception at execution time if used.

         .. versionadded:: 1.7

     * - maxTimeMS
       - integer
       - .. include:: /includes/extracts/common-option-maxTimeMS.rst

         .. versionadded:: 1.3

     * - session
       - :php:`MongoDB\Driver\Session <class.mongodb-driver-session>`
       - .. include:: /includes/extracts/common-option-session.rst

         .. versionadded:: 1.3

     * - writeConcern
       - :php:`MongoDB\Driver\WriteConcern <class.mongodb-driver-writeconcern>`
       - .. include:: /includes/extracts/collection-option-writeConcern.rst

         .. include:: /includes/extracts/common-option-writeConcern-transaction.rst

Return Values
-------------

The name of the created index as a string.

Errors/Exceptions
-----------------

.. include:: /includes/extracts/error-unsupportedexception.rst
.. include:: /includes/extracts/error-invalidargumentexception.rst
.. include:: /includes/extracts/error-driver-runtimeexception.rst

Examples
--------

Create a Compound Index
~~~~~~~~~~~~~~~~~~~~~~~

The following example creates a :manual:`compound index </core/index-compound>`
on the ``borough`` and ``cuisine`` fields in the ``restaurants`` collection in
the ``test`` database.

.. code-block:: php

   <?php

   $collection = (new MongoDB\Client)->selectCollection('test', 'restaurants');

   $indexName = $collection->createIndex(['borough' => 1, 'cuisine' => 1]);

   var_dump($indexName);

The output would then resemble:

.. code-block:: none

   string(19) "borough_1_cuisine_1"

Create a Partial Index
~~~~~~~~~~~~~~~~~~~~~~

The following example adds a :manual:`partial index </core/index-partial>` on
the ``borough`` field in the ``restaurants`` collection in the ``test``
database. The partial index indexes only documents where the ``borough`` field
exists.

.. code-block:: php

   <?php

   $collection = (new MongoDB\Client)->selectCollection('test', 'restaurants');

   $indexName = $collection->createIndex(
      ['borough' => 1],
      [
          'partialFilterExpression' => [
              'borough' => ['$exists' => true],
          ],
      ]
   );

   var_dump($indexName);

The output would then resemble:

.. code-block:: none

   string(9) "borough_1"

See Also
--------

- :phpmethod:`MongoDB\Collection::createIndexes()`
- :doc:`/tutorial/indexes`
- :manual:`createIndexes </reference/command/createIndexes>` command reference
  in the MongoDB manual
- :manual:`Index </indexes>` documentation in the MongoDB Manual
