Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB: WriteResult.getN() always returns 0?

According to the javaDoc, getN() method of WriteResult class in MongoDB-java returns the number of documents updated in the opertion. But it always returns zero, even if the document is inserted correctly.

Why so? or I understood it wrongly?

like image 861
vivek_jonam Avatar asked Feb 15 '13 11:02

vivek_jonam


1 Answers

Note that regardless of what the MongoDB documentation states, the WriteResult.getN() method always returns 0 for insert using the Java driver, regardless of the number of objects inserted. The source code for setting the "n" field in the 2.12.3 of the Java driver:

if (type == INSERT) {
  commandResult.put("n", 0);
} else if (type == REMOVE) {
  commandResult.put("n", bulkWriteResult.getRemovedCount());
} else if (type == UPDATE || type == REPLACE) {
  commandResult.put("n", bulkWriteResult.getMatchedCount() + bulkWriteResult.getUpserts().size());
  if (bulkWriteResult.getMatchedCount() > 0) {
    commandResult.put("updatedExisting", true);
  } else {
    commandResult.put("updatedExisting", false);
  }
  if (!bulkWriteResult.getUpserts().isEmpty()) {
    commandResult.put("upserted", bulkWriteResult.getUpserts().get(0).getId());
  }
}

But errors are correctly reported via Exceptions. For example, a MongoException will be thrown when inserting a document that violates a unique index, if WriteConcern specified is at least the ACKNOWLEDGED

like image 122
wbdarby Avatar answered Nov 11 '22 05:11

wbdarby