Spring MongoRepository is updating or upserting instead of inserting

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.

Edit: Check your repository version, insert was introduced in version 1.7.

Leave a Comment