Using $set and $setOnInsert during upsert
<p>I'm trying to update a collection in mongodb and if a field exists, will insert it. I'm not so sure how can I do that with the upsert option.</p>

<pre><code>MongoCollection&lt;Document&gt; docs = mongoDb.getCollection("users");
Bson filterQuery = new Document("userId", userId).append("fileType", fileType);
Bson updateQuery = new Document("$set", new Document("fileType", fileType).append("fileName", fileName).append("fileSize", fileSize).append("userId", userId).append("lastModifiedTimestamp", new Timestamp(System.currentTimeMillis())));
updateQuery.append("$setOnInsert", new Document("creationTimestamp", new Timestamp(System.currentTimeMillis())));
docs.updateOne(filterQuery, updateQuery, (new UpdateOptions()).upsert(true));
</code></pre>

<p>This is not working. I'm not updating the same fields for $set and $setOnInsert but not sure why this isn't working. Any thoughts?</p>