2016-11-25 74 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