对于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-如果批量写入操作中存在异常
MongoException-如果由于其他一些失败而导致写入失败
但是,异常会导致该异常,如果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()
,则可以使用完全相同的代码,因为它抛出与(MongoBulkWrite, MongoException)
相同的异常insertMany()
,请参见BulkWrite()如果要更新代码以捕获其他异常,则可以轻松扩展:
查看要从日志中捕获的异常的特定消息和错误代码。
添加一个if块,作为我为该特定错误代码提供的块,以使用正则表达式提取ID,并将其添加到针对此类错误而初始化的数组中
最后做你的处理
关于java - 如何在批量操作中无法插入/删除/更新文档的数组_ids?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35521262/