How to ignore duplicate documents when using insertMany in mongodb php library?

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 // This option is not working ]); 

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?

+5
source share
1 answer

Try replacing the "conntinueOnError" parameter with "ordered" set to false based on the documentation, when the order parameter is set to false, insertMany will continue to write even if one record failed.

Here is the link to the documentation: insertMany

+3
source

Source: https://habr.com/ru/post/1260373/


All Articles