How to upsert with mongodb-java-driver

user1312837 picture user1312837 · Jun 26, 2013 · Viewed 32.1k times · Source

How can I upsert data into mongodb collection with java-driver?

I try (with empty collection):

db.getCollection(collection).update(new BasicDBObject("_id", "12"), dbobject, true, false);

But document was created with _id == ObjectID(...). Not with "12" value.

This code (js) add document with _id = "12" as expected

db.metaclass.update(
   { _id:12},
   {
     $set: {b:1}
   },
   { upsert: true }
)

mongo-java-driver-2.11.2

Answer

prayagupd picture prayagupd · Nov 28, 2015

If you are using mongo-java driver 3, following .updateOne() method with {upsert, true} flag works.

 void setLastIndex(MongoClient mongo, Long id, Long lastIndexValue) {

    Bson filter = Filters.eq("_id", id);

    Bson update =  new Document("$set",
                  new Document()
                        .append("lastIndex", lastIndexValue)
                        .append("created", new Date()));
    UpdateOptions options = new UpdateOptions().upsert(true);

    mongo.getDatabase(EventStreamApp.EVENTS_DB)
         .getCollection(EventCursor.name)
         .updateOne(filter, update, options);
  }