How do we know if a document was saved in Mongodb after the save () method?

I save my document in MongoDb and use the save method with the class, collection name param.

All save and paste methods are an invalid return type. then how can I know if my document has been saved or not.

This is what I have to re-request in order to check if my document is saved. I just need some kind of return value to find out if it is stored.

In addition, I use Spring Data for Mongo to perform operations.

+6
source share
2 answers

It depends on what you use WriteConcern . If you use WriteConcern.ACKNOWLEDGED , the operation will wait for confirmation from the main server, therefore, if no exception is thrown, the record was saved correctly. Otherwise, you will be able to request WriteResult

 WriteResult writeResult=mycollection.insert(record); if (writeResult.getError() != null) { throw new Exception(String.format("Insertion wasn't successful: %s",writeResult)); } 
+3
source

org.springframework.data.mongodb.repository.MongoRepository

returns a list of saved objects:

 <S extends T> List<S> save(Iterable<S> entites); 

or

 CrudRepository 

you have

 <S extends T> S save(S entity); 

which provides a stored object. This object will have any field that you annotated using @Id with a value filled in different null values ​​after it was successfully saved.

+2
source

All Articles