Marc Marc - 5 months ago 196
Java Question

Spring MongoRepository is updating or upserting instead of inserting

I'm using a :

org.springframework.data.mongodb.repository.MongoRepository


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

repository.save(object);


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
world
and then to another save :

repository.save(newObject);


Results : the save works but updates the original object.

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

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

Answer

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.