I am using mongo php library and trying to insert some old data into mongodb. I used the insertMany() method and passed a huge array of documents that may have duplicate documents at unique indexes.
Suppose I have a collection of users and these indexes:
[ { "v" : 1, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "test.users" }, { "v" : 1, "unique" : true, "key" : { "email" : 1 }, "name" : "shop_id_1_title_1", "ns" : "test.users" } ]
If there is a duplicate document, MongoDB\Driver\Exception\BulkWriteException will raise and stop the process. I want to find a way to ignore the insertion of duplicate documents (as well as preventing promotion due to exception) and continue to insert other documents.
I found in php.net the documentation with the continueOnError flag, which does the trick, but it seems that it does not work with this library.
Example from php.net:
<?php $con = new Mongo; $db = $con->demo; $doc1 = array( '_id' => new MongoId('4cb4ab6d7addf98506010001'), 'id' => 1, 'desc' => "ONE", ); $doc2 = array( '_id' => new MongoId('4cb4ab6d7addf98506010002'), 'id' => 2, 'desc' => "TWO", ); $doc3 = array( '_id' => new MongoId('4cb4ab6d7addf98506010002'), // same _id as above 'id' => 3, 'desc' => "THREE", ); $doc4 = array( '_id' => new MongoId('4cb4ab6d7addf98506010004'), 'id' => 4, 'desc' => "FOUR", ); $c = $db->selectCollection('c'); $c->batchInsert( array($doc1, $doc2, $doc3, $doc4), array('continueOnError' => true) );
And how I tried to use the flag with mongo php library :
<?php $users = (new MongoDB\Client)->test->users $collection->insertMany([ [ 'username' => 'admin', 'email' => ' admin@example.com ', 'name' => 'Admin User', ], [ 'username' => 'test', 'email' => ' test@example.com ', 'name' => 'Test User', ], [ 'username' => 'test 2', 'email' => ' test@example.com ', 'name' => 'Test User 2', ], ], [ 'continueOnError' => true
The code above still throws an exception and doesn't seem to work. Is there another option flag or is there a way to do this?