在mongodb php库中使用insertMany时如何忽略重复的文档? [英] how to ignore duplicate documents when using insertMany in mongodb php library?
问题描述
我正在使用 mongo php库,并尝试将一些旧数据插入mongodb .我使用了insertMany()
方法并传递了大量文档,这些文档可能在唯一索引上有重复的文档.
I am using mongo php library, and trying to insert some old data into mongodb. I used insertMany()
method and pass a huge array of document, that may have duplicate documents on unique indexes.
让我们说我有一个用户集合,并具有以下索引:
Lets say I have a users collection and have these indexes:
[
{
"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
将引发并停止该过程.我想找到一种方法来忽略插入重复的文档(并防止引发异常)并继续插入其他文档.
If there's a duplicate document, MongoDB\Driver\Exception\BulkWriteException
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.
我在 php.net 文档中找到了一个名为continueOnError
的标志可以解决问题,但似乎无法在该库中使用.
I found in php.net documentation a flag called continueOnError
that do the trick but it seems that it's not working with this library.
来自php.net的示例:
The example from 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库中使用标志的方式:>
And the way I tried to use the flag with mongo php library:
<?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
]);
上面的代码仍然引发异常,并且似乎不起作用. 是否还有其他选项标志或有任何方法可以做到这一点?
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?
推荐答案
根据文档,尝试将"continueOnError"选项替换为"ordered"设置为false,根据文档,当ordered选项设置为false时,insertMany将继续写入,即使一次写入失败.
Try to replace 'continueOnError' option by 'ordered' set to false, based on the documentation, when ordered option is set to false the insertMany will continue writing, even if a single write fails.
这是docs链接: insertMany
这篇关于在mongodb php库中使用insertMany时如何忽略重复的文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!