0

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.

Jens Schauder
  • 77,657
  • 34
  • 181
  • 348
  • Does this answer your question? [How do I partially update an object in MongoDB so the new object will overlay / merge with the existing one](https://stackoverflow.com/questions/10290621/how-do-i-partially-update-an-object-in-mongodb-so-the-new-object-will-overlay) – Jens Schauder Jun 09 '21 at 05:22

1 Answers1

0

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.

titogeo
  • 2,156
  • 2
  • 24
  • 41