<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <title>Creates an index on the specified field(s) if it does not already exist</title> </head> <body><div class="manualnavbar" style="text-align: center;"> <div class="prev" style="text-align: left; float: left;"><a href="mongocollection.drop.html">MongoCollection::drop</a></div> <div class="next" style="text-align: right; float: right;"><a href="mongocollection.find.html">MongoCollection::find</a></div> <div class="up"><a href="class.mongocollection.html">MongoCollection</a></div> <div class="home"><a href="index.html">PHP Manual</a></div> </div><hr /><div id="mongocollection.ensureindex" class="refentry"> <div class="refnamediv"> <h1 class="refname">MongoCollection::ensureIndex</h1> <p class="verinfo">(PECL mongo >=0.9.0)</p><p class="refpurpose"><span class="refname">MongoCollection::ensureIndex</span> — <span class="dc-title"> Creates an index on the specified field(s) if it does not already exist </span></p> </div> <div class="refsect1 description" id="refsect1-mongocollection.ensureindex-description"> <h3 class="title">Description</h3> <div class="methodsynopsis dc-description"> <span class="modifier">public</span> <span class="type">bool</span> <span class="methodname"><strong>MongoCollection::ensureIndex</strong></span> ( <span class="methodparam"><span class="type"><span class="type string|array">string|array</span></span> <code class="parameter">$key|keys</code></span> [, <span class="methodparam"><span class="type">array</span> <code class="parameter">$options</code><span class="initializer"> = array()</span></span> ] )</div> <div class="warning"><strong class="warning">Warning</strong> <p class="para"> This method is deprecated since version 1.5.0. Please use <span class="methodname"><a href="mongocollection.createindex.html" class="methodname">MongoCollection::createIndex()</a></span> instead. </p> </div> <p class="para"> Creates an index on the specified field(s) if it does not already exist. Fields may be indexed with a direction (e.g. ascending or descending) or a special type (e.g. text, geospatial, hashed). </p> <blockquote class="note"><p><strong class="note">Note</strong>: <p class="para"> This method will use the <a href="https://docs.mongodb.com/manual/reference/command/createIndexes" class="link external">» createIndexes</a> database command when communicating with MongoDB 2.6+. For previous database versions, the method will perform an insert operation on the special <em>system.indexes</em> collection. </p> </p></blockquote> </div> <div class="refsect1 parameters" id="refsect1-mongocollection.ensureindex-parameters"> <h3 class="title">Parameters</h3> <p class="para"> <dl> <dt> <code class="parameter">keys</code> </dt> <dd> <p class="para"> An array specifying the index's fields as its keys. For each field, the value is either the index direction or <a href="https://docs.mongodb.com/manual/core/index-types/" class="link external">» index type</a>. If specifying direction, specify <em>1</em> for ascending or <em>-1</em> for descending. </p> </dd> <dt> <code class="parameter">options</code> </dt> <dd> <p class="para"> An array of options for the index creation. Currently available options include: <ul class="itemizedlist"> <li class="listitem"><p class="para"><em>"unique"</em></p><p class="para">Specify <strong><code>TRUE</code></strong> to create a unique index. The default value is <strong><code>FALSE</code></strong>. This option applies only to ascending/descending indexes.</p><blockquote class="note"><p><strong class="note">Note</strong>: <p class="para">When MongoDB indexes a field, if a document does not have a value for the field, a <strong><code>NULL</code></strong> value is indexed. If multiple documents do not contain a field, a unique index will reject all but the first of those documents. The <em>"sparse"</em> option may be used to overcome this, since it will prevent documents without the field from being indexed.</p></p></blockquote></li> <li class="listitem"><p class="para"><em>"sparse"</em></p><p class="para">Specify <strong><code>TRUE</code></strong> to create a sparse index, which only indexes documents containing a specified field. The default value is <strong><code>FALSE</code></strong>.</p></li> <li class="listitem"><p class="para"><em>"expireAfterSeconds"</em></p><p class="para">The value of this option should specify the number of seconds after which a document should be considered expired and automatically removed from the collection. This option is only compatible with single-field indexes where the field will contain <a href="class.mongodate.html" class="classname">MongoDate</a> values.</p><blockquote class="note"><p><strong class="note">Note</strong>: <p class="para">This feature is available in MongoDB 2.2+. See <a href="https://docs.mongodb.com/manual/tutorial/expire-data/" class="link external">» Expire Data from Collections by Setting TTL</a> for more information.</p></p></blockquote></li> <li class="listitem"><p class="para"><em>"name"</em></p><p class="para">A optional name that uniquely identifies the index.</p><blockquote class="note"><p><strong class="note">Note</strong>: <p class="para">By default, the driver will generate an index name based on the index's field(s) and ordering or type. For example, a compound index <em>array("x" => 1, "y" => -1)</em> would be named <em>"x_1_y_-1"</em> and a geospatial index <em>array("loc" => "2dsphere")</em> would be named <em>"loc_2dsphere"</em>. For indexes with many fields, it is possible that the generated name might exceed MongoDB's <a href="https://docs.mongodb.com/manual/reference/limits/#Index-Name-Length" class="link external">» limit for index names</a>. The <em>"name"</em> option may be used in that case to supply a shorter name.</p></p></blockquote></li> <li class="listitem"><p class="para"><em>"background"</em></p><p class="para">Builds the index in the background so that building an index does <em class="emphasis">not</em> block other database activities. Specify <strong><code>TRUE</code></strong> to build in the background. The default value is <strong><code>FALSE</code></strong>.</p><div class="warning"><strong class="warning">Warning</strong><p class="para">Prior to MongoDB 2.6.0, index builds on secondaries were executed as foreground operations, irrespective of this option. See <a href="https://docs.mongodb.com/manual/tutorial/build-indexes-on-replica-sets/" class="link external">» Building Indexes with Replica Sets</a> for more information.</p></div></li> <li class="listitem"><p class="para"><em>"socketTimeoutMS"</em></p><p class="para">This option specifies the time limit, in milliseconds, for socket communication. If the server does not respond within the timeout period, a <a href="class.mongocursortimeoutexception.html" class="classname">MongoCursorTimeoutException</a> will be thrown and there will be no way to determine if the server actually handled the write or not. A value of <em>-1</em> may be specified to block indefinitely. The default value for <a href="class.mongoclient.html" class="classname">MongoClient</a> is <em>30000</em> (30 seconds).</p></li> </ul> </p> <p class="para"> The following option may be used with MongoDB 2.6+: <ul class="itemizedlist"> <li class="listitem"><p class="para"><em>"maxTimeMS"</em></p><p class="para">Specifies a cumulative time limit in milliseconds for processing the operation on the server (does not include idle time). If the operation is not completed by the server within the timeout period, a <a href="class.mongoexecutiontimeoutexception.html" class="classname">MongoExecutionTimeoutException</a> will be thrown.</p></li> </ul> </p> <p class="para"> The following options may be used with MongoDB versions before 2.8: <ul class="itemizedlist"> <li class="listitem"><p class="para"><em>"dropDups"</em></p><p class="para">Specify <strong><code>TRUE</code></strong> to force creation of a unique index where the collection may contain duplicate values for a key. MongoDB will index the first occurrence of a key and delete all subsequent documents from the collection that contain a duplicate value for that key. The default value is <strong><code>FALSE</code></strong>.</p><div class="warning"><strong class="warning">Warning</strong><p class="para"><em>"dropDups"</em> may delete data from your database. Use with extreme caution.</p></div><blockquote class="note"><p><strong class="note">Note</strong>: <p class="para">This option is not supported on MongoDB 2.8+. Index creation will fail if the collection contains duplicate values.</p></p></blockquote></li> </ul> </p> <p class="para"> The following options may be used with MongoDB versions before 2.6: <ul class="itemizedlist"> <li class="listitem"><p class="para"><em>"w"</em></p><p class="para">See <a href="mongo.writeconcerns.html" class="link">Write Concerns</a>. The default value for <a href="class.mongoclient.html" class="classname">MongoClient</a> is <em>1</em>.</p></li> <li class="listitem"><p class="para"><em>"wTimeoutMS"</em></p><p class="para">This option specifies the time limit, in milliseconds, for <a href="mongo.writeconcerns.html" class="link">write concern</a> acknowledgement. It is only applicable when <em>"w"</em> is greater than <em>1</em>, as the timeout pertains to replication. If the write concern is not satisfied within the time limit, a <a href="class.mongocursorexception.html" class="classname">MongoCursorException</a> will be thrown. A value of <em>0</em> may be specified to block indefinitely. The default value for <a href="class.mongoclient.html" class="classname">MongoClient</a> is <em>10000</em> (ten seconds).</p></li> </ul> </p> <p class="para"> The following options are deprecated and should no longer be used: <ul class="itemizedlist"> <li class="listitem"><p class="para"><em>"safe"</em></p><p class="para">Deprecated. Please use the <a href="mongo.writeconcerns.html" class="link">write concern</a> <em>"w"</em> option.</p></li> <li class="listitem"><p class="para"><em>"timeout"</em></p><p class="para">Deprecated alias for <em>"socketTimeoutMS"</em>.</p></li> <li class="listitem"><p class="para"><em>"wtimeout"</em></p><p class="para">Deprecated alias for <em>"wTimeoutMS"</em>.</p></li> </ul> </p> </dd> </dl> </p> </div> <div class="refsect1 returnvalues" id="refsect1-mongocollection.ensureindex-returnvalues"> <h3 class="title">Return Values</h3> <p class="para"> Returns an array containing the status of the index creation. The array contains whether the operation succeeded (<em>"ok"</em>), the number of indexes before and after the operation (<em>"numIndexesBefore"</em> and <em>"numIndexesAfter"</em>), and whether the collection that the index belongs to has been created (<em>"createdCollectionAutomatically"</em>). If the index already existed and did not need to be created, a <em>"note"</em> field may be present in lieu of <em>"numIndexesAfter"</em>. </p> <p class="para"> With MongoDB 2.4 and earlier, a status document is only returned if the <a href="mongo.writeconcerns.html" class="link">write concern</a> is at least <em>1</em>. Otherwise, <strong><code>TRUE</code></strong> is returned. The fields in the status document are different, except for the <em>"ok"</em> field, which signals whether the index creation was successful. Additional fields are described in the documentation for <span class="function"><a href="mongocollection.insert.html" class="function">MongoCollection::insert()</a></span>. </p> </div> <div class="refsect1 changelog" id="refsect1-mongocollection.ensureindex-changelog"> <h3 class="title">Changelog</h3> <p class="para"> <table class="doctable informaltable"> <thead> <tr> <th>Version</th> <th>Description</th> </tr> </thead> <tbody class="tbody"> <tr> <td>1.5.0</td> <td> <p class="para"> Renamed the <em>"wtimeout"</em> option to <em>"wTimeoutMS"</em>. Emits <strong><code>E_DEPRECATED</code></strong> when <em>"wtimeout"</em> is used. </p> <p class="para"> Renamed the <em>"timeout"</em> option to <em>"socketTimeoutMS"</em>. Emits <strong><code>E_DEPRECATED</code></strong> when <em>"timeout"</em> is used. </p> <p class="para"> Emits <strong><code>E_DEPRECATED</code></strong> when <em>"safe"</em> is used. </p> </td> </tr> <tr> <td>1.3.4</td> <td>Added <em>"wtimeout"</em> option.</td> </tr> <tr> <td>1.3.0</td> <td> <p class="para">Added <em>"w"</em> option.</p> <p class="para"> The <code class="parameter">options</code> parameter no longer accepts a boolean to signify a unique index. Instead, this now has to be done with <em>array('unique' => true)</em>. </p> </td> </tr> <tr> <td>1.2.11</td> <td> Emits <strong><code>E_DEPRECATED</code></strong> when <code class="parameter">options</code> is <span class="type"><span class="type scalar">scalar</span></span>. </td> </tr> <tr> <td>1.2.0</td> <td>Added <em>"timeout"</em> option.</td> </tr> <tr> <td>1.0.11</td> <td> <p class="para"> The <em>"safe"</em> option will trigger a primary failover, if necessary. </p> <p class="para"> <a href="class.mongoexception.html" class="classname">MongoException</a> will be thrown if the index name (either generated or set) is longer than 128 bytes. </p> </td> </tr> <tr> <td>1.0.5</td> <td> Added the <em>"name"</em> option to override index name creation. </td> </tr> <tr> <td>1.0.2</td> <td> Changed <code class="parameter">options</code> parameter from boolean to array. Pre-1.0.2, the second parameter was an optional boolean value specifying a unique index. </td> </tr> </tbody> </table> </p> </div> <div class="refsect1 errors" id="refsect1-mongocollection.ensureindex-errors"> <h3 class="title">Errors/Exceptions</h3> <p class="para"> Throws <a href="class.mongoexception.html" class="classname">MongoException</a> if the index name is longer than 128 bytes, or if the index specification is not an array. </p> <p class="para"> Throws <a href="class.mongoduplicatekeyexception.html" class="classname">MongoDuplicateKeyException</a> if the server could not create the unique index due to conflicting documents. </p> <p class="para"> Throws <a href="class.mongoresultexception.html" class="classname">MongoResultException</a> if the server could not create the index due to an error. </p> <p class="para">Throws <a href="class.mongocursorexception.html" class="classname">MongoCursorException</a> if the <em>"w"</em> option is set and the write fails.</p><p class="para">Throws <a href="class.mongocursortimeoutexception.html" class="classname">MongoCursorTimeoutException</a> if the <em>"w"</em> option is set to a value greater than one and the operation takes longer than <var class="varname"><var class="varname">MongoCursor::$timeout</var></var> milliseconds to complete. This does not kill the operation on the server, it is a client-side timeout. The operation in <var class="varname"><var class="varname">MongoCollection::$wtimeout</var></var> is milliseconds.</p> </div> <div class="refsect1 examples" id="refsect1-mongocollection.ensureindex-examples"> <h3 class="title">Examples</h3> <div class="example" id="mongocollection.aggregate.example.zipcode.explain"> <p><strong>Example #1 <span class="function"><strong>MongoCollection::ensureIndex()</strong></span> example</strong></p> <div class="example-contents"> <div class="phpcode"><code><span style="color: #000000"> <span style="color: #0000BB"><?php<br /><br />$c </span><span style="color: #007700">= new </span><span style="color: #0000BB">MongoCollection</span><span style="color: #007700">(</span><span style="color: #0000BB">$db</span><span style="color: #007700">, </span><span style="color: #DD0000">'foo'</span><span style="color: #007700">);<br /><br /></span><span style="color: #FF8000">// create an index on 'x' ascending<br /></span><span style="color: #0000BB">$c</span><span style="color: #007700">-></span><span style="color: #0000BB">ensureIndex</span><span style="color: #007700">(array(</span><span style="color: #DD0000">'x' </span><span style="color: #007700">=> </span><span style="color: #0000BB">1</span><span style="color: #007700">));<br /><br /></span><span style="color: #FF8000">// create a unique index on 'y'<br /></span><span style="color: #0000BB">$c</span><span style="color: #007700">-></span><span style="color: #0000BB">ensureIndex</span><span style="color: #007700">(array(</span><span style="color: #DD0000">'y' </span><span style="color: #007700">=> </span><span style="color: #0000BB">1</span><span style="color: #007700">), array(</span><span style="color: #DD0000">'unique' </span><span style="color: #007700">=> </span><span style="color: #0000BB">true</span><span style="color: #007700">));<br /><br /></span><span style="color: #FF8000">// create a compound index on 'za' ascending and 'zb' descending<br /></span><span style="color: #0000BB">$c</span><span style="color: #007700">-></span><span style="color: #0000BB">ensureIndex</span><span style="color: #007700">(array(</span><span style="color: #DD0000">'za' </span><span style="color: #007700">=> </span><span style="color: #0000BB">1</span><span style="color: #007700">, </span><span style="color: #DD0000">'zb' </span><span style="color: #007700">=> -</span><span style="color: #0000BB">1</span><span style="color: #007700">));<br /><br /></span><span style="color: #0000BB">?></span> </span> </code></div> </div> </div> <div class="example" id="example-1582"> <p><strong>Example #2 Geospatial Indexing</strong></p> <div class="example-contents"><p> Mongo supports geospatial indexes, which allow you to search for documents near a given location or within a shape. The following example creates a geospatial index on the <em>"loc"</em> field: </p></div> <div class="example-contents"> <div class="phpcode"><code><span style="color: #000000"> <span style="color: #0000BB"><?php<br /><br />$collection</span><span style="color: #007700">-></span><span style="color: #0000BB">ensureIndex</span><span style="color: #007700">(array(</span><span style="color: #DD0000">'loc' </span><span style="color: #007700">=> </span><span style="color: #DD0000">'2dsphere'</span><span style="color: #007700">));<br /><br /></span><span style="color: #0000BB">?></span> </span> </code></div> </div> </div> <div class="example" id="example-1583"> <p><strong>Example #3 Drop duplicates example</strong></p> <div class="example-contents"> <div class="phpcode"><code><span style="color: #000000"> <span style="color: #0000BB"><?php<br /><br />$collection</span><span style="color: #007700">-></span><span style="color: #0000BB">insert</span><span style="color: #007700">(array(</span><span style="color: #DD0000">'username' </span><span style="color: #007700">=> </span><span style="color: #DD0000">'joeschmoe'</span><span style="color: #007700">));<br /></span><span style="color: #0000BB">$collection</span><span style="color: #007700">-></span><span style="color: #0000BB">insert</span><span style="color: #007700">(array(</span><span style="color: #DD0000">'username' </span><span style="color: #007700">=> </span><span style="color: #DD0000">'joeschmoe'</span><span style="color: #007700">));<br /><br /></span><span style="color: #FF8000">/* Index creation fails, since you cannot create a unique index on a field when<br /> * duplicates exist.<br /> */<br /></span><span style="color: #0000BB">$collection</span><span style="color: #007700">-></span><span style="color: #0000BB">ensureIndex</span><span style="color: #007700">(array(</span><span style="color: #DD0000">'username' </span><span style="color: #007700">=> </span><span style="color: #0000BB">1</span><span style="color: #007700">), array(</span><span style="color: #DD0000">'unique' </span><span style="color: #007700">=> </span><span style="color: #0000BB">1</span><span style="color: #007700">));<br /><br /></span><span style="color: #FF8000">/* MongoDB will one of the conflicting documents and allow the unique index to<br /> * be created.<br /> */<br /></span><span style="color: #0000BB">$collection</span><span style="color: #007700">-></span><span style="color: #0000BB">ensureIndex</span><span style="color: #007700">(array(</span><span style="color: #DD0000">'username' </span><span style="color: #007700">=> </span><span style="color: #0000BB">1</span><span style="color: #007700">), array(</span><span style="color: #DD0000">'unique' </span><span style="color: #007700">=> </span><span style="color: #0000BB">1</span><span style="color: #007700">, </span><span style="color: #DD0000">'dropDups' </span><span style="color: #007700">=> </span><span style="color: #0000BB">1</span><span style="color: #007700">));<br /><br /></span><span style="color: #FF8000">/* We now have a unique index and subsequent inserts with the same username will<br /> * fail.<br /> */<br /></span><span style="color: #0000BB">$collection</span><span style="color: #007700">-></span><span style="color: #0000BB">insert</span><span style="color: #007700">(array(</span><span style="color: #DD0000">'username' </span><span style="color: #007700">=> </span><span style="color: #DD0000">'joeschmoe'</span><span style="color: #007700">));<br /><br /></span><span style="color: #0000BB">?></span> </span> </code></div> </div> </div> </div> <div class="refsect1 seealso" id="refsect1-mongocollection.ensureindex-seealso"> <h3 class="title">See Also</h3> <ul class="simplelist"> <li class="member"><span class="methodname"><a href="mongocollection.createindex.html" class="methodname" rel="rdfs-seeAlso">MongoCollection::createIndex()</a> - Creates an index on the specified field(s) if it does not already exist</span></li> <li class="member"><span class="methodname"><a href="mongocollection.deleteindex.html" class="methodname" rel="rdfs-seeAlso">MongoCollection::deleteIndex()</a> - Deletes an index from this collection</span></li> <li class="member"><span class="methodname"><a href="mongocollection.deleteindexes.html" class="methodname" rel="rdfs-seeAlso">MongoCollection::deleteIndexes()</a> - Delete all indices for this collection</span></li> <li class="member"> The MongoDB <a href="https://docs.mongodb.com/manual/indexes/" class="link external">» index</a> and <a href="https://docs.mongodb.com/manual/core/index-types/" class="link external">» index type</a> documentation. </li> </ul> </div> </div><hr /><div class="manualnavbar" style="text-align: center;"> <div class="prev" style="text-align: left; float: left;"><a href="mongocollection.drop.html">MongoCollection::drop</a></div> <div class="next" style="text-align: right; float: right;"><a href="mongocollection.find.html">MongoCollection::find</a></div> <div class="up"><a href="class.mongocollection.html">MongoCollection</a></div> <div class="home"><a href="index.html">PHP Manual</a></div> </div></body></html>