Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know if document was saved in MongoDb after save() method?

I am saving my document in MongoDb and using save method with class,collection name param.

All the methods of save and insert are void return type. then how i can know that my document was saved or not.

Is it that i have to re-query to check whether my document was saved. I just need any return value to see if it was saved.

Moreover i am using Spring Data for Mongo to do operations.

like image 294
usman Avatar asked Nov 23 '15 09:11

usman


People also ask

What does save () in MongoDB return?

The save() returns a WriteResult() object that contains the status of the insert or update operation.

How do I save a file in MongoDB?

In MongoDB, use GridFS for storing files larger than 16 MB. In some situations, storing large files may be more efficient in a MongoDB database than on a system-level filesystem. If your filesystem limits the number of files in a directory, you can use GridFS to store as many files as needed.

Where are documents stored in MongoDB?

By default Mongo stores its data in the directory /data/db . You can specify a different directory using the --dbpath option. If you're running Mongo on Windows then the directory will be C:\data\db , where C is the drive letter of the working directory in which Mongo was started.

How are documents stored in MongoDB?

Documents are used to store data in MongoDB. These documents are saved in JSON (JavaScript Object Notation) format in MongoDB. JSON documents support embedded fields, allowing related data and data lists to be stored within the document rather than in an external table. JSON is written in the form of name/value pairs.


2 Answers

It depends on what WriteConcern are you using. If you use WriteConcern.ACKNOWLEDGED, the operation will wait for an acknowledgement from the primary server, so if no exception is raised, the record has been saved correctly. Otherwise you should be able to query WriteResult

WriteResult writeResult=mycollection.insert(record);
if (writeResult.getError() != null) {
    throw new Exception(String.format("Insertion wasn't successful: %s",writeResult));
 }
like image 78
Alex Avatar answered Oct 25 '22 17:10

Alex


org.springframework.data.mongodb.repository.MongoRepository

returns a list of the saved objects:

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

or in

CrudRepository

you have

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

which provides the saved object. That object will have a whatever field you annotated with @Id with a value filled in different to null after it has successfully been persisted.

like image 43
ricardoespsanto Avatar answered Oct 25 '22 18:10

ricardoespsanto