Marc Marc - 3 months ago 125x
Java Question

Spring MongoRepository is updating or upserting instead of inserting

I'm using a :

I start with an empty DB and create an object with
_id = 1234
for example, and set some other String field to
for example, and then do:;

All is well, it saves the document in MondoDB.

I create a NEW object, set the same
_id = 1234
but set the other String field to
and then to another save :;

Results : the save works but updates the original object.

Expected results: This should fail with a
is unique and I am using 2 separate objects when doing each save.

Defect in spring or am I doing something wrong ???


Save, by definition, is supposed to update an object in the upsert style, update if present and insert if not. Read the save operation documentation on the MongoDb website

The insert operation in mongodb has the behavior you expect, but from the MongoRepository documentation it appears that insert is delegated to save so it won't make any difference. But you can give that a try and see if it works for you. Otherwise you can just do a get before to check if the object exists, since it is an index lookup it will be fast.