Find and Upsert Using the Java Driver
Nope. You want .findOneAndUpdate()
:
FindOneAndUpdateOptions options = new FindOneAndUpdateOptions() .upsert(true) .returnDocument(ReturnDocument.AFTER);UpdateResult ret = getMongoCollection().findOneAndUpdate(query, update, options);
The .replaceOne()
means exactly that and "replaces" the entire document ( except the _id
) with the content provided. That means modifiers like $inc
are not allowed here.
So you use .findOneAndUpdate()
instead. Note that you likely want ReturnDocument.AFTER
to return the "modified" document rather than the "original" document before the update was applied, which would be the default action.