MongoDB: WriteResult.getN() always returns 0?

前端 未结 3 2106
隐瞒了意图╮
隐瞒了意图╮ 2021-01-17 12:47

According to the javaDoc, getN() method of WriteResult class in MongoDB-java returns the number of documents updated in the opertion. But it always

3条回答
  •  遥遥无期
    2021-01-17 13:18

    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:

    getLastError.n reports the number of documents updated or removed, if the preceding operation was an update or remove operation.

    An insert being neither an update nor a remove, 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:

    > db.test.insert({_id: 'test'})
    > db.getLastErrorObj()
    { "n" : 0, "connectionId" : 7, "err" : null, "ok" : 1 }
    

    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:

    • my previous argument hinges on your WriteConcern being high enough that errors are reported. If you're using WriteConcern.NONE, for example, no exception will ever be raised.
    • if the number of updated documents is an absolute must for you, you can always use save instead of insert. Not very clean, but it behaves the way you seem to expect.

提交回复
热议问题