Spring SimpleMongoRepository save behaviour

Consider the following Java Class.

class Transaction {
@Id
public String id;
public String firstProperty;
public String secondProperty;
} 

class TransactionRepository extends MongoRepository<TransactionInfo , String> {
...
}

In Java following code is executed :

Transaction transaction = new Transaction("T1");
transaction.setFirstProperty("first");
transactionRepository.save(transaction);

Following document is created.

{
_id:123,
firstProperty: "first"
}

If this piece of code is executed later :

Transaction transaction = new Transaction("T1");
transaction.setSecondProperty("second");
transactionRepository.save(transaction);

Expected Document :

{
_id:123,
firstProperty: "first",
secondProperty: "second"
}

Actual Document:

{
_id:123,
secondProperty: "second"
}

From what I read in MongoDB docs I expect the document to be updated with “secondProperty” but it results in the removal of “firstProperty” . I think the document is getting created again, instead of getting updated. Please let me know if I am missing something.

Hi @Sandeep_Siddaramaiah and welcome in the MongoDB Community :muscle: !

Save != Update.

Save replaces the entire document ─ based on the _id by the new one while an update applies the transformation.

See the doc:

https://docs.mongodb.com/manual/reference/method/db.collection.save/#replace-an-existing-document

If you want to add a new field, you should use an update with the $set operator.

Cheers,
Maxime.

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.