Reputation: 7605
I'm trying to execute a blocking call to db.collection.insert(List<DBObject>, WriteConcern)
method with the MongoDB java driver. No matter what I use in WriteConcern: SAFE
, FSYNC_SAFE
, FSYNCED
, ACKNOWLEDGED
, ... I can't grant the write has been performed...at least not the way I'm doing it right now. Check the code:
WriteResult result = collection.insert(list, WriteConcern.FSYNC_SAFE);
if (result.getN()> 0){
System.out.println("Alleluyah!");
return true;
}
From what I've read here, FSYNC_SAFE
, should be the way to go... The data is being written, but the call to result.getN()
is always zero. If there is no way to check if a write has been completed...
Why create the getN()
method in the first place?? Any idea of what I'm doing wrong? I do need to check this insert has been performed. I can query the collection and check, but it just looks overkill to me...
Thanks!
Upvotes: 3
Views: 1646
Reputation: 105
Check out this post regarding the getN()
method. It only gives information on the number of documents affected by an update or remove operation.
I'm no expert but consider this quote from the MongoDB wiki on the getLastError
method:
You should actually use a write concern like
WriteConcern.ACKNOWLEDGED
instead of callinggetLastError()
manually.
As far as I understand it using a sufficient level of WriteConcern
and getting a WriteResult
back means that the operation was successful and no error occurred. Check out the article and reference on WriteConcern in the wiki as well.
Since you explicitly want to verify that the insert operation executed correctly you could do something like this:
WriteResult result = collection.insert(list, WriteConcern.FSYNC_SAFE);
CommanResult commandResult = result.getLastError();
if (commandResult.get("err") != null) {
System.out.println("Alleluyah");
return true;
}
Inserting a document with WriteConcern.FSYNC_SAFE
calls the getLastError()
method - source. If the level of WriteConcern
isn't strict enough calling getLastError()
may result in an error - examine the WriteResult code on github . If no error has occurred than the err field will be null
, otherwise it will contain an error message - source.
Upvotes: 4