diff --git a/reference/mongo/mongocollection/ensureindex.xml b/reference/mongo/mongocollection/ensureindex.xml index 5924088eca..fcf770e018 100644 --- a/reference/mongo/mongocollection/ensureindex.xml +++ b/reference/mongo/mongocollection/ensureindex.xml @@ -14,8 +14,8 @@ &reftitle.description; public booleanMongoCollection::ensureIndex - string|arraykeys - booleanunique + arraykeys + arrayoptions A unique index cannot be created on a field if multiple existing documents do not contain the field. The field is effectively &null; for these documents and thus already non-unique. @@ -38,11 +38,32 @@ - unique + options - If the index should be unique. + This parameter is an associative array of the form + array("optionname" => <boolean>, ...). Currently + supported options are: + + + + "unique" + + + Create a unique index. + + + + + "dropDups" + + + If a unique index is being created and duplicate values exist, drop + all but one duplicate value. + + + @@ -57,6 +78,32 @@ + + &reftitle.changelog; + + + + + + &Version; + &Description; + + + + + 1.0.2 + + Changed "options" parameter from boolean to array. Pre-1.0.2, the + second parameter was an optional boolean value specifying a unique + index. + + + + + + + + &reftitle.examples; @@ -68,19 +115,43 @@ $c = new MongoCollection($db, 'foo'); // create an index on 'x' ascending -$c->ensureIndex('x'); - -// create an index on 'y' ascending -$c->ensureIndex(array('y' => 1)); - -// create an index on 'w' descending -$c->ensureIndex(array('w' => -1)); +$c->ensureIndex(array('x' => 1)); // create an index on 'z' ascending and 'zz' descending $c->ensureIndex(array('z' => 1, 'zz' => -1)); // create a unique index on 'x' -$c->ensureIndex(array('x' => 1), true); +$c->ensureIndex(array('x' => 1), array("unique" => true)); + +?> +]]> + + + + Drop duplicates example + +insert(array("username" => "joeschmoe")); +$collection->insert(array("username" => "joeschmoe")); + +/* + * index creation fails, you can't create a unique index on a key with + * non-unique values + */ +$collection->ensureIndex(array("username" => 1), array("unique" => 1)); + +/* + * index creation succeeds: one of the documents is removed from the collection + */ +$collection->ensureIndex(array("username" => 1), array("unique" => 1, "dropDups" => 1)); + +/* + * now we have a unique index, more inserts with the same username (such as the + * one below) will fail + */ +$collection->insert(array("username" => "joeschmoe")); ?> ]]>