Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在mongodb php库中使用insertMany时,如何忽略重复文档?_Php_Mongodb_Mongodb Php - Fatal编程技术网

在mongodb php库中使用insertMany时,如何忽略重复文档?

在mongodb php库中使用insertMany时,如何忽略重复文档?,php,mongodb,mongodb-php,Php,Mongodb,Mongodb Php,我正在使用,并试图将一些旧数据插入mongodb。我使用了insertMany()方法并传递了大量文档,这些文档可能在唯一索引上有重复的文档 假设我有一个用户集合,并有以下索引: [ { "v" : 1, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "test.users" }, { "v" : 1,

我正在使用,并试图将一些旧数据插入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"
    }
]
如果存在重复文档,
MongoDB\Driver\Exception\BulkWriteException
将引发并停止该进程。我想找到一种方法来忽略插入重复文档(同时防止引发异常),并继续插入其他文档

我在文档中发现了一个名为
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)
);

根据文档,尝试将“continueOnError”选项替换为设置为false的“ordered”,当ordered选项设置为false时,即使一次写入失败,insertMany也将继续写入


这里是文档链接:

您能更具体地说明什么似乎不起作用吗?您可以添加一个示例来帮助我们理解。@Veeram根据您的要求添加了更多详细信息和示例
<?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
]);