gpt4 book ai didi

java - mongo 3.3 中的 DBCollection save() 等效项

转载 作者:行者123 更新时间:2023-11-30 06:59:24 24 4
gpt4 key购买 nike

我们当前的实现是 mongo-java-driver:3.0.4文档更新如下 -

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

哪里param.toMap()实现为

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

mongo-java-driver:3.4.0-rc1我尝试的实现是使用 insertOne作为

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

考虑来源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.

但我怀疑 insertOne现在我使用它来实现与 save() 类似的效果以前。

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

问题 - 是否有任何类似的方式 save()当前MongoCollection方法?有没有办法使用_idParam或者在不使用它的情况下做类似的事情?

<小时/>

编辑:参数定义为 -

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

}

并且有一个 ParamCodec implements Codec<Param>使用 CodecRegistry 注册如下给客户:

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

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

MongoClient(addresses, clientOptions);

最佳答案

您可能想使用

findOneAndUpdate(Bson filter, Bson update, FindOneAndUpdateOptions options)

FindOneAndUpdateOptions 的 upsert 选项设置为 true。

您可以传递 _id 作为查询过滤器,将参数作为更新传递,当查询与 _id 匹配时,它将更新插入该值,如果未找到匹配项,它将插入一个新行。

关于java - mongo 3.3 中的 DBCollection save() 等效项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41187740/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com