How to upsert document in MongoDB Java driver 3 How to upsert document in MongoDB Java driver 3 mongodb mongodb

How to upsert document in MongoDB Java driver 3


In the Mongo Java Driver 3.0 series we added a new Crud API which is more explicit and therefore beginner friendly. This initiative has been rolled out over a number of MongoDB Drivers but it does contain some changes compared to the older API.

As you are not updating an existing document using an update operator, the updateOne method is not appropriate.

The operation you describe is a replaceOne operation and can be run like so:

sessionCollection.replaceOne(    "_id" -> new BsonString(sessionKey),    sessionDocument,    (new UpdateOptions()).upsert(true))