我正在使用mongo php library,并试图将一些旧数据插入到mongodb中。我使用insertMany()
方法并传递了一个巨大的文档数组,该数组可能在唯一索引上有重复的文档。
假设我有一个users集合,并具有以下索引:
[
{
"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
的标志,它可以做到这一点,但它似乎不适用于这个库。
来自www.example.com的示例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中使用flag的方式是:
<?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
]);
上面的代码仍然会引发异常,并且似乎不起作用。是否有其他选项标志或有任何方法可以做到这一点?
1条答案
按热度按时间ux6nzvsh1#
尝试将
continueOnError
选项替换为ordered
并将其设置为false
,根据文档,当ordered
选项设置为false
时,insertMany将继续写入,即使单个写入失败。以下是docs链接:insertMany