==================================
MongoDBCollection::createIndexes()
==================================

.. default-domain:: mongodb

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

.. phpmethod:: MongoDB\\Collection::createIndexes($indexes)
               
   Create one or more indexes for the collection.
   
   .. code-block:: php

      function createIndexes(array $indexes): string[]

   ``createIndex()`` has one parameter: ``$indexes``, which is an array
   or object.
   Each element in the ``$indexes`` array|object must have a
   "``key`` document" that specifies the fields to index and the
   array direction or type. You can then specify index options as
   additional key-value pairs in that element.

   For example, the following ``$indexes`` parameter creates an ascending
   unique index on the ``username`` field:
   
   .. code-block:: none
                   
      [ 'key' => ['username => 1 '], 'unique' => true ],
   
   The following ``$indexes`` parameter creates a 2dsphere index on the ``loc`` field and
   specifies a custom index name:
   
   .. code-block:: none
                   
      [ 'key' => [ 'loc' => '2dsphere'], 'name' => 'geo_index' ],
   
   You can specify any 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 </reference/command/createIndexes>`
   command reference in the MongoDB manual.

Output
------

Returns the name of the created indexes as an array of strings.
                
Example
-------

The following creates two indexes on the ``restaurants`` collection in
the ``example`` database. One index is a compound index on the
``borough`` and ``cuisine`` fields and the other is 2dsphere index
on the ``location`` field with a custom name.

.. code-block:: php
                
   <?php
   
   $database = new MongoDB\Client;

   $collection = $database->selectCollection('example','restaurants');

   $index = $collection->createIndexes(
       [ 
           [ 'key' => [ 'borough' => 1, 'cuisine' => 1] ],
           [ 'key' => [ 'location' => '2dsphere'], 'name' => 'geo_index'],
       ]);

   var_dump($index);

The output would resemble the following::

   array(2) {
     [0]=>
     string(19) "borough_1_cuisine_1"
     [1]=>
     string(9) "geo_index"
   }

.. seealso::
   
   - :phpmethod:`MongoDB\\Collection::createIndex`
   - :doc:`/tutorial/indexes`
   - :manual:`createIndexes </reference/command/createIndexes>` 
     command reference in the MongoDB manual
   - :manual:`Index documentation </indexes>`
