2016-11-25 76 views
5

我正在使用mongo php library,並試圖將一些舊數據插入到mongodb中。我使用了insertMany()方法並傳遞了大量文檔,這些文檔可能在唯一索引上有重複的文檔。如何在mongodb php庫中使用insertMany時忽略重複的文檔?

可以說我有一個用戶收集和有這些指標:

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

如果有一個複製文檔,MongoDB\Driver\Exception\BulkWriteException將提高,並停止該進程。我想找到一種方法來忽略插入重複文檔(並防止異常引發)並繼續插入其他文檔。

我在php.net文檔中找到一個名爲continueOnError的標誌,它可以做到這一點,但它似乎不適用於該庫。

從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) 
); 

我試圖用標誌與mongo php library方式:

<?php 

$users = (new MongoDB\Client)->test->users 

$collection->insertMany([ 
    [ 
     'username' => 'admin', 
     'email' => '[email protected]', 
     'name' => 'Admin User', 
    ], 
    [ 
     'username' => 'test', 
     'email' => '[email protected]', 
     'name' => 'Test User', 
    ], 
    [ 
     'username' => 'test 2', 
     'email' => '[email protected]', 
     'name' => 'Test User 2', 
    ], 
], 
[ 
    'continueOnError' => true // This option is not working 
]); 

上面的代碼仍然引發異常,似乎不工作。 是否有其他選項標誌或有任何方法來做到這一點?

+0

你能更具體,因爲它似乎是不工作?你可以添加一個例子來幫助我們理解。 – Veeram

+0

@Veeram根據您的要求添加更多詳細信息和示例 – Behzadsh

回答

3

根據文檔,嘗試用'ordered'替換'conntinueOnError'選項,當命令選項設置爲false時,insertMany將繼續寫入,即使單次寫入失敗。

這裏的文檔鏈接:insertMany