Search code examples
javamongodbmongo-java

mongoDB test the return value


I use mongoDB 3.0.1 in java application, I want to know how I can test the return value of DBCollection.insert(BasicDBObject),

For exemple, if the insert is done show message1 if not show message2.

I see that mongoDB use WriteResult as return and these's what I get when I print the WriteResult

WriteResult insert = dbCollection.insert(basicDBObject);
showMessageDialog(null,insert);

WriteResult{,n=0,updateOfExisting=false, upsertedld=null}

Solution

  • If you want to handle failure or acknowledge insert then,

    Refer http://api.mongodb.org/java/current/com/mongodb/WriteConcern.html

    You can use it per one write like this:

    dbCollection.insert(dbObj, WriteConcern.SAFE);
    

    If you use WriteConcern.SAFE your operation will wait for an acknowledgement from the primary server, so if no exception is raised then you're ok.

    You can check using WriteResult as well, If writeResult.getError() gives null, insert is done.