how to ignore duplicate documents when using insertMany in mongodb php library?
<p>I am using <a href="https://github.com/mongodb/mongo-php-library" rel="noreferrer">mongo php library</a>, and trying to insert some old data into mongodb. I used <code>insertMany()</code> method and pass a huge array of document, that may have duplicate documents on unique indexes.</p>

<p>Lets say I have a users collection and have these indexes:</p>

<pre><code>[
    {
        "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"
    }
]
</code></pre>

<p>If there's a duplicate document, <code>MongoDB\Driver\Exception\BulkWriteException</code> would raise and stop the process. I want to find a way to ignore inserting duplicate documents (and also preventing the exception from raise) and continue inserting other documents.</p>

<p>I found in <a href="http://php.net/manual/en/mongocollection.batchinsert.php" rel="noreferrer">php.net</a> documentation a flag called <code>continueOnError</code> that do the trick but it seems that it's not working with this library.</p>

<p>The example from php.net:</p>

<pre><code>&lt;?php

$con = new Mongo;
$db = $con-&gt;demo;

$doc1 = array(
        '_id' =&gt; new MongoId('4cb4ab6d7addf98506010001'),
        'id' =&gt; 1,
        'desc' =&gt; "ONE",
);
$doc2 = array(
        '_id' =&gt; new MongoId('4cb4ab6d7addf98506010002'),
        'id' =&gt; 2,
        'desc' =&gt; "TWO",
);
$doc3 = array(
        '_id' =&gt; new MongoId('4cb4ab6d7addf98506010002'), // same _id as above
        'id' =&gt; 3,
        'desc' =&gt; "THREE",
);
$doc4 = array(
        '_id' =&gt; new MongoId('4cb4ab6d7addf98506010004'),
        'id' =&gt; 4,
        'desc' =&gt; "FOUR",
);

$c = $db-&gt;selectCollection('c');
$c-&gt;batchInsert(
    array($doc1, $doc2, $doc3, $doc4),
    array('continueOnError' =&gt; true)
);
</code></pre>

<p>And the way I tried to use the flag with <a href="https://github.com/mongodb/mongo-php-library" rel="noreferrer">mongo php library</a>:</p>

<pre><code>&lt;?php

$users = (new MongoDB\Client)-&gt;test-&gt;users

$collection-&gt;insertMany([
    [
        'username' =&gt; 'admin',
        'email' =&gt; 'admin@example.com',
        'name' =&gt; 'Admin User',
    ],
    [
        'username' =&gt; 'test',
        'email' =&gt; 'test@example.com',
        'name' =&gt; 'Test User',
    ],
    [
        'username' =&gt; 'test 2',
        'email' =&gt; 'test@example.com',
        'name' =&gt; 'Test User 2',
    ],
],
[
    'continueOnError' =&gt; true    // This option is not working
]);
</code></pre>

<p>The code above still raise the exception, and seems not to work.
Is there other option flag or is there any way to do this?</p>