如何在批量操作中获取文档的数组 _ids 失败 insert/delete/update?

How do I get array _ids of documents failed to insert/delete/update in bulk operation?

bulkWrite() 的情况下,我想要成功处理文档或失败文档的 _id 数组,以及失败原因。

以下是我的尝试。如果可能,建议更简单的方法。

try {
    collection.insertMany(documents, new InsertManyOptions().ordered(false));
} catch (DuplicateKeyException dke) {
    LOGGER.error("{}", dke);
} catch (MongoBulkWriteException mbwe) {
    List<BulkWriteError> errors = mbwe.getWriteErrors();
    for (BulkWriteError error : errors) {
        LOGGER.error("{}", error.getMessage());
    }
} catch (Exception ex) {
    LOGGER.error("{}", ex.getCause());
}

当我插入具有重复 _id 的文档时,我应该根据 javadoc 得到 DuplicateKeyException,但我得到 MongoBulkWriteException。

我正在使用 java 8 和 mongodb 3.2.1 驱动程序

insertMany 仅抛出以下异常:

  • MongoBulkWriteException - if there's an exception in the bulk write operation

  • MongoException - if the write failed due some other failure

但是异常会导致它的原因,并且在重复 id 的情况下将类似于:

insertDocument :: caused by :: 11000 E11000 duplicate key error index: test.restaurants.$_id_  dup key: { : ObjectId('56c8ac3146235e4898bb696c') }

因此,由于消息中包含信息,因此您可以使用正则表达式提取数组中失败文档的 ID。

代码应该是这样的(我在你的代码中内联):

        List<String>duplicateIds = new ArrayList<String>();
        List<BulkWriteError> errors = mbwe.getWriteErrors();
        for (BulkWriteError error : errors) {

            LOGGER.error("{}", error.getMessage());

            // extract from error.message the id of the duplicated document, (11000 is the duplicate id code)
            if (error.getCode() == 11000) {
                Matcher m = Pattern.compile("[0-9a-f]{24}")
                        .matcher(error.getMessage());
                m.find();
                duplicateIds.add(m.group());
            }

        }
        // here the duplicateIds will hold all the found ids, you can print them in console for example:
        System.out.println(duplicateIds.toString());
        // and do whatever else you like with them

上面的代码将捕获重复的 ID - 如果你想让它捕获其他错误,很容易相应地调整它。

更新:

如果您想使用 bulkWrite(),您可以使用完全相同的代码,因为它会抛出与 insertMany() 相同的异常 (MongoBulkWrite, MongoException),请参阅 BulkWrite()

如果您想更新代码以捕获其他异常,它很容易扩展:

  1. 查看您要从日志中捕获的异常的具体消息和错误代码。
  2. 添加一个 if 块作为我为该特定错误代码提供的块,以使用正则表达式提取 ID 并将它们添加到您为此类错误初始化的数组中
  3. 最后做你的处理