问题描述
我们正在将Mongo从2.x版本升级到3.x,我的任务是将旧的(Java)代码更新为所有版本的新版本,试图避免使用不推荐使用的方法,但尝试更改功能尽可能少.我没有写代码的原始版本.
We are upgrading our Mongo from version 2.x to 3.x, and I am given the task of updating our old (Java) code to the new version of everything, trying to avoid deprecated methods but otherwise trying to change functionality as little as possible. I did not write the original version of the code.
以下更改令我感到困惑.以前,我们使用DBCollection.insert(args)
返回一个WriteResult
对象.现在我们应该使用MongoCollection.insertOne(args)
,但这不会返回任何内容.还有另一种产生WriteResult
对象的方法吗?
The following change I find confusing. Before, we used DBCollection.insert(args)
which returned a WriteResult
object. Now we should use MongoCollection.insertOne(args)
, but this returns nothing. Is there another way to produce a WriteResult
object?
或者Mongo开发团队是否认为不需要WriteResult
对象?我可以看到我们正在以一种非必要的方式使用它(仅记录日志),但我不想在没有充分理由的情况下将其删除.
Or is the opinion of the Mongo dev team that WriteResult
objects are not necessary? I can see that we are using it in a fairly inessential way (just logging) but I don't want to remove it without good reason.
以上所有内容也适用于insertMany
,我认为它的答案相同或相似.
All the above also applies to insertMany
, and I assume it would have the same or similar answer.
推荐答案
insertOne()
方法提供了一些优势来处理有问题的情况,例如insert
需要一些手动检查,例如
insertOne()
method gives some advantages to handle the problematic situations where as insert
required some manual checks, for e.g
1.)它支持Error Handling
,这意味着您必须在try-catch
块中使用插入代码,这只能告诉您出现了问题(例如为唯一索引插入重复的条目),所以请执行其他操作,而不是执行当前操作
1.) it support Error Handling
mean you have to use your insert code in try-catch
block which simply can tell you , something went wrong (like inserting duplicate entries for unique indexes)so do something else instead of current flow.
InsertOne返回:
MongoWriteException - if the write failed due some other failure specific to the insert command
MongoWriteConcernException - if the write failed due being unable to fulfill the write concern
MongoException - if the write failed due some other failure
因此,您可以简单地添加三个catch块来处理所有可能的插入失败,并且如果未引发异常,则意味着数据已成功插入(无需检查任何内容,可以快速继续),并且代码将类似于
So you can simply add three catch blocks to handle all possibilities of insertion failure and if no exception is thrown mean data inserted successfully (no need to check anything , move on quickly ) and code will be like
try {
.. insert query
}catch(MongoWriteException e){ .. handle something wrong with query}
catch(MongoWriteConcernException e){ .. handle something wrong with write-concern}
catch(MongoException e){ .. handle something else(unknown) went wrong}
咨询:您将获得
-
try-catch
好的做法可以减少代码出现问题的情况
try-catch
a good practice result in less problematic code
这篇关于将Mongo升级到3.x;插入不再返回WriteResult的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!