Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to upsert with mongodb-java-driver

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

like image 896
user1312837 Avatar asked Jun 26 '13 11:06

user1312837


People also ask

How do you use Upsert in Java?

To specify an upsert with the updateOne() or updateMany() methods, pass true to UpdateOptions. upsert() . To specify an upsert with the replaceOne() method, pass true to ReplaceOptions.

Is there an Upsert option in the MongoDB insert command?

insert() provides no upsert possibility.

Can I connect MongoDB with Java?

Connecting via Java. Assuming you've resolved your dependencies and you've set up your project, you're ready to connect to MongoDB from your Java application. Since MongoDB is a document database, you might not be surprised to learn that you don't connect to it via traditional SQL/relational DB methods like JDBC.


2 Answers

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);
  }
like image 57
prayagupa Avatar answered Oct 17 '22 12:10

prayagupa


You cannot set _id if dbobject is just a document and does not contain an update operator eg: $set, $setOnInsert.

Just passing a document will replace the whole document meaning it doesn't set an _id a falls back to ObjectId

So your example works if you use an update operator eg:

db.getCollection(collection).update(
    new BasicDBObject("_id", "12"), 
    new BasicDBObject("$set", new BasicDBObject("Hi", "world")), true, false)
like image 18
Ross Avatar answered Oct 17 '22 13:10

Ross