我的应用程序主要通过使用mongodb java驱动程序3.2.2对mongodb进行插入操作。
我会收到一个我必须插入的文档,大约90%的时间,我在我的collection上定义了两个唯一的键索引。偶尔当我收到一个重复元素时,我依赖于驱动程序抛出我是一个异常DuplicateKeyException,我知道我想要更新文档。
我的文档如下所示:
{_id:{Object....},
name:"something", //unique key
rollNo:1232, //unique key combined with name
otherfields
}
我的Java代码如下所示。
try{
dbCollections.insert(dbObject);
}catch(DuplicateKeyException e){
// since it is duplicate , lets just update it,
}
我有以下问题
答案 0 :(得分:1)
您可以使用UPSERT标志ref将插入更改为更新,这将减少异常处理,并插入ID不存在的新文档,还可以节省网络流量。
UpdateResult updateOne(Bson filter,
Bson update,
UpdateOptions updateOptions)
Update a single document in the collection according to the specified arguments.
Parameters:
filter - a document describing the query filter, which may not be null.
update - a document describing the update, which may not be null. The update to apply must include only update operators.
updateOptions - the options to apply to the update operation
Returns:
the result of the update one operation
Throws:
MongoWriteException - if the write failed due some other failure specific to the update command
MongoWriteConcernException - if the write failed due being unable to fulfil the write concern
MongoException - if the write failed due some other failure