zee
zee

Reputation: 502

Save A List of Documents in MongoDB through Morphia excluding Duplicates

I am trying to save a list of documents in mongodb through morphia.

Entity:

class test {
  @Id
  private ObjectId  id;
  private String email_id;
}

The Entity has a unique index on a email_id field. I am saving the list of test entity using;

datastore.save(list_of_test_entity);

what i want is if the list contains a Test entity that is a duplicate, dont insert that but continue adding rest.

is it possible with save() method?

Upvotes: 0

Views: 795

Answers (1)

s7vr
s7vr

Reputation: 75934

You can use the insert variants with continueOnError flag set to false which signals server to do unordered write operations on AdvancedDatastore.

AdvancedDatastore uses BulkWrites. This will continue with processing all writes and will throw the last in the order it processed as DuplicateKeyException. So you can add try catch to ignore the error.

AdvancedDatastore datastore = (AdvancedDatastore) morphia.createDatastore(mongoClient, dbName);
InsertOptions insertOptions = new InsertOptions();
insertOptions.continueOnError(true);
try {
datastore.insert(list_of_test_entity, insertOptions);
catch (DuplicateKeyException e){
  //Ignore
}

Upvotes: 1

Related Questions