javamongodbmongodb-javamongodb-java-3.3.0

DBCollection save() equivalent in mongo 3.3


Our current implementation with mongo-java-driver:3.0.4 for a document update is as follows -

private void updateParam(String param1, String param2) {
    Param param = new Param(param1, param2);
    DBCollection collection = mongoClient.getDB("databaseName").getCollection("collectionName");
    collection.save(new BasicDBObject(param.toMap()));
}

where param.toMap() is implemented as

public Map<String, Object> toMap() {
    return JSONObjectMapper.getObjectMapper().convertValue(this, Map.class);
}

With mongo-java-driver:3.4.0-rc1 the implementation I tried was using insertOne as

private void updateParam(String param1, String param2) {
    Param param = new Param(param1, param2);
    MongoCollection<Param> mongoCollection = mongoClient.getDatabase("databaseName").getCollection("collectionName", Param.class);
    mongoCollection.insertOne(param);
}

Considering the information from source DBCollection's save

  • If a document does not exist with the specified '_id' value, the method performs an insert with the specified fields in the document.
  • If a document exists with the specified '_id' value, the method performs an update, replacing all field in the existing record with the fields from the document.

But I doubt the insertOne implementation now that I am using it for the similar effect as to the save() previously.

Inserts the provided document. If the document is missing an identifier, the driver should generate one

Question - Is there any similar way as of save() with current MongoCollection approach? Is there a way to use _id of Param or do something similar without using it as well?


Edit : Param is defined as -

public class Param {

  private String param2;
  private String param2;

  public Param() {
  }

  public Param(String param1, String param2) {
    this.param1 = param1;
    this.param2 = param2;
  }

  public Map<String, Object> toMap() {
    return JSONObjectMapper.getObjectMapper().convertValue(this, Map.class);
  }

}

and has a ParamCodec implements Codec<Param> which is registered using CodecRegistry as follows to the client :

CodecRegistry codecRegistry = CodecRegistries.fromRegistries(MongoClient.getDefaultCodecRegistry(),
            CodecRegistries.fromCodecs(new ParamCodec()));

MongoClientOptions clientOptions = new MongoClientOptions.Builder()
    ....
    .codecRegistry(codecRegistry)
    .build();

MongoClient(addresses, clientOptions);

Solution

  • You may want to use

    findOneAndUpdate(Bson filter, Bson update, FindOneAndUpdateOptions options)
    

    with FindOneAndUpdateOptions with upsert option set to true.

    You can pass the _id as the query filter and param as your update and when the query matches the _id it will upsert the value and if no match is found it will insert a new row.