问题
I want to check if an insert
fails (due to unique=True index in the collection). If there is an error do something. Bellow is an example of my code.
DBCollection user...;
BasicDBObject Doc = new BasicDBObject(... );
String user_exists = user.insert(Doc).getError(); //insert the doc get error if any
if(user_exists!=null){ //any errors?
user.update(new BasicDBObject(...)); // error exists so do smthng
}
The above as it is does not work. I believe that the String user_exists
is always null. How can I make the above work?
I have seen similar SO questions and mention the WriteConcern which can be passed in the insert()
. E.g.
coll.insert(dbObj, WriteConcern.SAFE);
sources: SO question or Mongo docs
However I do not know which one field should I pass (SAFE, ACKNOWLEDGED, UNACKNOWLEDGED etc..) in order to get the error. Maybe I'm pointed in the wrong direction.
I do not wish to raise an exception just to check if there is an error returned by the insert
operation.
回答1:
If you are using WriteConcern.ACKNOWLEDGED
(which I think is also SAFE
) you don't need to pollute your code with error checking.
For ACKNOWLEDGED
, the driver will automatically issue a getLastError
command automatically and raise an exception if anything got wrong, for example duplicate index violation.
Starting from v2.10 of the Java Driver, the default Write Concern is ACKNOWLEDGED
EDIT
I do not wish to raise an exception just to check if there is an error returned by the insert operation.
You shouldn't do this, but in any case:
The insert
method indeed returns WriteResult
. If it's getError()
is null
, everything is OK, otherwise it returns something such as E11000 duplicate key error index:...
. For this to work, you will have to use WriteConcern.UNACKNOWLEDGED
来源:https://stackoverflow.com/questions/21588871/check-if-there-is-an-error-in-update-insert-mongodb-java-driver