Spring MongoRepository is updating or upserting instead of inserting Spring MongoRepository is updating or upserting instead of inserting spring spring

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.


the application shall update only when you have @Id annotation for one of the field, after long difficulty had found this

@Document(collection="bus")public class Bus {//  @Indexed(unique=true, direction=IndexDirection.DESCENDING, dropDups=true)    @Id    private String busTitle;     private int totalNoOfSeats;    private int noOfSeatsAvailable;     private String busType; }

but somehow I could not use @Indexed(unique=true, direction=IndexDirection.DESCENDING, dropDups=true)