これらの値のいずれにも一意のインデックスを指定していないため、同様の情報を持つ複数のレコードを挿入できます。デフォルトの一意のインデックスは on になります_id
。
MongoCollection.ensureIndexを使用して、PHP から独自のインデックスを定義できます。
// create a unique index on 'phonenum'
$collection->ensureIndex(array('phonenum' => 1), array("unique" => true));
また、一意のインデックスに関する MongoDB のドキュメントも読む価値があります。既に重複または null 値を持つ可能性がある既存のコレクションに対して一意のインデックスが作成されている場合は、注意すべき点がいくつかあります。
_id
使用するより自然な主キーがある場合は、独自の値を指定するオプションもあります。_id
ただし、これが新しい挿入に対して一意で あることを確認する必要があります。
MongoDB によって作成されるデフォルトのObjectIDは、割り当て時に一意である可能性がかなり高くなるように設計されています。
コード例:
<?php
// Connect to MongoDB server
$mongo = new Mongo();
// Use database 'mydb' and collection 'mycoll'
$collection = $mongo->mydb->mycoll;
// Drop this collection for TESTING PURPOSES ONLY
$collection->drop();
// The document details to insert
$document = array(
'asda' => 12312,
'cxzcxz' => 'czczcxz',
);
try {
$collection->insert($document, array("safe" => true));
// Note that $collection->insert() adds the _id of the document inserted
echo "Saved with _id:", $document['_id'], "\n";
}
catch (MongoCursorException $e) {
echo "Error: " . $e->getMessage()."\n";
}
// Add unique index for field 'asda'
$collection->ensureIndex(array('asda' => 1), array("unique" => true));
// Try to insert the same document again
$document = array(
'asda' => 12312,
'cxzcxz' => 'czczcxz',
);
try {
$collection->insert($document, array("safe" => true));
echo "Saved with _id:", $document['_id'], "\n";
}
catch (MongoCursorException $e) {
echo "Error: " . $e->getMessage()."\n";
}
?>