Springboot Mongo DB Insert Many without duplicates

I am working on a SpringBoot Application and using insertMany method to insert a list of Objects to DB.
Is there an API which will take care of not inserting duplicates?

For Example, if I have an Object Employee with EmployeeName and EmployeeNumber.
example data

{
   "EmployeeName":"Alex",
   "EmployeeNumber":"1"
}
{
   "EmployeeName":"Ben",
   "EmployeeNumber":"2"
}

If the DB already contains Employee 1 with employee name as Abel , when I try to insertMany with both the employees in the list
is there a way to get Employee 1 name update and Employee name inserted rather than ending up with
a
1 Abel
2 Ben
1 Alex

Hello @ivin_jacob
Thanks for reaching out!!To achieve the desired result for the operation:

  1. You can enforce uniqueness of a field using unique indexes. The syntax for creating a unique index in this particular case would be db.collection.createIndex({EmployeeNumber:1}, {unique:true})
  2. Update on the existing document can be carried out with upsert(), and MongoDB provides API called bulkOperation to carry out operations on bulk data. Please refer to the documentation below. BulkOperations (Spring Data MongoDB 3.3.1 API)
  3. Also, there have been issues with unique index content not being enforced in older versions, (https://jira.mongodb.org/browse/SERVER-58936), so would strongly suggest to use the latest MongoDB versions(5.0.6, 4.4.12, 4.2.18), if not using Atlas.

Please feel free to reach out for further queries.Thanks
Aasawari

2 Likes