Mongodb java api: WriteResult#getN()

java, mongodb

Solution

From the GetLastError() documentation

The return value from the command is an object with various fields. The common fields are listed below; there may also be other fields.

- ok - true indicates the getLastError command completed successfully. This does NOT indicate there wasn't a last error.

- err - if non-null, indicates an error occurred. Value is a textual description of the error.

- code - if set, indicates the error code which occurred. connectionId - the id of the connection

- lastOp - the op-id from the last operation

For updates:

- n - if an update was done, this is the number of documents updated.

So in this context, 'get "n" field' means get n which is the number of documents updated. Without "multi" being set to true it can only be either 0 or 1.

Problem

I'm writing some Java code using MongoDB with Java API and I'm unsure of some part of the Javadoc. In a multi-thread context I use DBCollection.html#update(com.mongodb.DBObject, com.mongodb.DBObject) to update a unique document, but I saw that two threads could try to write concurrently. In this context, I observed that only one write was done, as Mongodb seems to use optimistic write lock, but I wanted to find out programmatically in which thread the write was the one who wrote, and which one was not. As a "no update" behavior was silent (I mean no exception or something), I searched into the API some way to answer my issue and after some tests found out this method: WriteResult#getN() ``` public int getN() Gets the "n" field Returns: ``` The description is, hum... not really exhaustive. My tests showed that the thread that win the write has a getN() that return 1, and the other 0. So my question is: Could someone confirm this ?

Original source