【问题标题】:how to ignore duplicate documents when using insertMany in mongodb php library?在 mongodb php 库中使用 insertMany 时如何忽略重复文档?
【发布时间】:2016-11-25 19:23:02
【问题描述】:

我正在使用mongo php library,并尝试将一些旧数据插入 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 会提出并停止该过程。我想找到一种方法来忽略插入重复文档(并防止引发异常)并继续插入其他文档。

我在 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' => '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
]);

上面的代码仍然引发异常,并且似乎不起作用。 是否有其他选项标志或有什么方法可以做到这一点?

【问题讨论】:

  • 你能说得更具体一些吗?您可以添加一个例子来帮助我们理解。
  • @Veeram 根据您的要求添加更多详细信息和示例

标签: php mongodb mongodb-php


【解决方案1】:

尝试将 'continueOnError' 选项替换为 'ordered' 设置为 false,根据文档,当 ordered 选项设置为 false 时 insertMany 将继续写入,即使单个写入失败。

这里是文档链接:insertMany

【讨论】:

    猜你喜欢
    • 2021-08-11
    • 1970-01-01
    • 2017-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-07
    • 2020-08-12
    • 1970-01-01
    相关资源
    最近更新 更多