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?
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?
You may also want to check http://docs.mongodb.org/manual/core/write-concern/
The dafault behaviour is not to use the "safe" write concern
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:
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
I was under the impression that this was the normal MongoDB behaviour, and has nothing to do with the Java driver.
The only thing I can find in the documentation is this:
An
insert
being neither anupdate
nor aremove
,n
doesn't seem to be specified and 0 is as good a default value as any. You can check it easily enough in the mongo shell:Unless I'm mistaken, it's not really an issue: ask yourself under which circumstances the insert would fail (other than, say, a connection failure). The only one I can think of is a unicity constraint violation, which would result in an exception. So almost by definition, the fact that you receive a
WriteResult
instance at all means the operation was successful and a document was inserted.A couple of notes:
WriteConcern
being high enough that errors are reported. If you're usingWriteConcern.NONE
, for example, no exception will ever be raised.save
instead ofinsert
. Not very clean, but it behaves the way you seem to expect.