Skip to content

Instantly share code, notes, and snippets.

@christeredvartsen
Last active April 3, 2017 17:03
Show Gist options
  • Save christeredvartsen/d3571902e0b981e5950a5e8110bbcaa8 to your computer and use it in GitHub Desktop.
Save christeredvartsen/d3571902e0b981e5950a5e8110bbcaa8 to your computer and use it in GitHub Desktop.
MongoDuplicateKeyException from MongoClient
<?php
$client = new MongoClient();
$client->selectDB('test')->drop();
$collection = $client->selectCollection('test', 'image');
$collection->createIndex(
['user' => 1, 'imageIdentifier' => 1],
['unique' => true]
);
$collection->insert([
'user' => 'christer',
'imageIdentifier' => 'image1',
]);
try {
$collection->insert([
'user' => 'christer',
'imageIdentifier' => 'image1',
]);
} catch (MongoDuplicateKeyException $e) {
var_dump($e->getMessage()); // string(167) "localhost:27017: insertDocument :: caused by :: 11000 E11000 duplicate key error index: test.image.$user_1_imageIdentifier_1 dup key: { : "christer", : "image1" }"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment