title: How to upsert document in MongoDB Java driver 3
body: <p>what is the idiomatic way to upsert a document using version 3 of the mongodb java driver (specifically v3.0.1)?</p>
  
  <p>We have a collection for sessions and when a new session gets created or modified, we want to upsert it in one operation - rather than having to query if a document exists yet and then either inserting or replacing.</p>
  
  <p>Our old upsertion code used the scala driver casbah 2.7.3.  It looked like:</p>
  
  <pre><code>import com.mongodb.casbah.MongoCollection
  import com.mongdb.DBObject
  val sessionCollection: MongoCollection = ...
  val sessionKey: String = ...
  val sessionDocument: DBObject = ... // Either create a new one, or find and modify an existing one
  
  sessionCollection.update(
      "_id" -&gt; sessionKey,
      sessionDocument
      upsert = true
  )
  </code></pre>
  
  <p>In our current project we're just using the plain java 3.0.1 driver and we're using <code>BsonDocument</code> instead of <code>DBObject</code> to make it more typsafe. I tried to replace the above with something like:</p>
  
  <pre><code>import com.mongodb.client.MongoCollection
  val sessionCollection: MongoCollection = ...
  val sessionKey: String = ...
  val sessionDocument: BsonDocument = // Either create a new one, or find and modify an existing one
  
  val updateOptions = new UpdateOptions
  updateOptions.upsert(true)
  
  sessionCollection.updateOne(
      "_id" -&gt; new BsonString(sessionKey),
      sessionDocument,
      updateOptions
  )
  </code></pre>
  
  <p>This throws the error "java.lang.IllegalArgumentException: Invalid BSON field name ...". The error is covered in <a href="https://stackoverflow.com/questions/29434207/mongodb-update-using-java-3-driver">this question</a> but the op in that question wasn't trying to upsert in one operation - they were using context to decide whether to replace/update/insert etc...</p>
  
  <p>I'm happy with code samples in scala or java.</p>
  
  <p>Thanks!</p>