How to upsert with mongodb-java-driver

前端 未结 4 1194
傲寒
傲寒 2020-12-31 02:06

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

I try (with empty collection):

db.getCollection(collection).update(new BasicDBObject(         


        
4条回答
  •  时光说笑
    2020-12-31 02:30

    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);
      }
    

提交回复
热议问题