Good day. It is necessary to insert from the list of entities only those that are new, without updating existing ones.
How to ignore during creation those entities that are already in the collection and add only new ones using Spring.
Good day. It is necessary to insert from the list of entities only those that are new, without updating existing ones.
How to ignore during creation those entities that are already in the collection and add only new ones using Spring.
I solved this problem as follows:
using the following method:
com.mongodb.client.MongoCollection # insertMany (java.util.List <? extends TDocument>, com.mongodb.client.model.InsertManyOptions)
Option used with flag order - false
new InsertManyOptions().ordered(false)
;
In details:
The entity List needs to be transformed into List of <org.bson.Document>, and then used in the request. As a result, the request will look like this:
public void createOnlyNew(List<Document> list) {
InsertManyOptions insertManyOptions = new InsertManyOptions().ordered(false);
try {
mongoTemplate.getCollection("name_of_collection").insertMany(list, insertManyOptions);
} catch (MongoBulkWriteException ignore) {
}
}
As a result of this request, only new entities will be added, while the existing ones in the database will remain unchanged.
An important detail: if mongo collides with an existing entity, com.mongodb.MongoBulkWriteException will be thrown. Therefore, I wrapped the request in a try catch block to ignore this exception. It should be noted that if this request is called inside a transactional method (for example, marked with the org.springframework.transaction.annotation.Transactional annotation), then the transaction will be considered completed with an error.