How to upsert document in MongoDB Java driver 3 -


what idiomatic way upsert document using version 3 of mongodb java driver (specifically v3.0.1)?

we have collection sessions , when new session gets created or modified, want upsert in 1 operation - rather having query if document exists yet , either inserting or replacing.

our old upsertion code used scala driver casbah 2.7.3. looked like:

import com.mongodb.casbah.mongocollection import com.mongdb.dbobject val sessioncollection: mongocollection = ... val sessionkey: string = ... val sessiondocument: dbobject = ... // either create new one, or find , modify existing 1  sessioncollection.update(     "_id" -> sessionkey,     sessiondocument     upsert = true ) 

in our current project we're using plain java 3.0.1 driver , we're using bsondocument instead of dbobject make more typsafe. tried replace above like:

import com.mongodb.client.mongocollection val sessioncollection: mongocollection = ... val sessionkey: string = ... val sessiondocument: bsondocument = // either create new one, or find , modify existing 1  val updateoptions = new updateoptions updateoptions.upsert(true)  sessioncollection.updateone(     "_id" -> new bsonstring(sessionkey),     sessiondocument,     updateoptions ) 

this throws error "java.lang.illegalargumentexception: invalid bson field name ...". error covered in this question op in question wasn't trying upsert in 1 operation - using context decide whether replace/update/insert etc...

i'm happy code samples in scala or java.

thanks!

in mongo java driver 3.0 series added new crud api more explicit , therefore beginner friendly. initiative has been rolled out on number of mongodb drivers contain changes compared older api.

as not updating existing document using update operator, updateone method not appropriate.

the operation describe replaceone operation , can run so:

sessioncollection.replaceone(     "_id" -> new bsonstring(sessionkey),     sessiondocument,     (new updateoptions()).upsert(true) ) 

Comments