Beh*_*dsh 18 php mongodb mongodb-php
我正在使用mongo php库,并尝试将一些旧数据插入mongodb.我使用了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"
}
]
Run Code Online (Sandbox Code Playgroud)
如果存在重复文档,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)
);
Run Code Online (Sandbox Code Playgroud)
我尝试使用mongo php库的标志的方式:
<?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
]);
Run Code Online (Sandbox Code Playgroud)
上面的代码仍然引发异常,似乎无法正常工作.是否有其他选项标志或有任何方法可以做到这一点?
You*_*neL 15
尝试将'ordered'设置为false的'conntinueOnError'选项替换为false,基于文档,当ordered命令选项设置为false时,insertMany将继续写入,即使单个写入失败也是如此.
这是docs链接:insertMany
| 归档时间: |
|
| 查看次数: |
10143 次 |
| 最近记录: |