3

I have a file to store in mongoDB. What I want is to avoid loading the whole file (which could be several MBs in size) instead I want to open the stream and direct it to mongoDB to keep the write operation performant. I dont mind storing the content in base64 encoded byte[].

Afterwards I want to do the same at the time of reading the file i.e. not to load the whole file in memory, instead read it in a stream.

I am currently using hibernate-ogm with Vertx server but I am open to switch to a different api if it servers the cause efficiently.

I want to actually store a document with several fields and several attachments.

Obaid Maroof
  • 1,523
  • 2
  • 19
  • 40

1 Answers1

3

You can use GridFS. Especially when you need to store larger files (>16MB) this is the recommended method:

File f = new File("sample.zip");
GridFS gfs = new GridFS(db, "zips");
GridFSInputFile gfsFile = gfs.createFile(f);
gfsFile.setFilename(f.getName());
gfsFile.setId(id);
gfsFile.save();

Or in case you have an InputStream in:

GridFS gfs = new GridFS(db, "zips");
GridFSInputFile gfsFile = gfs.createFile(in);
gfsFile.setFilename("sample.zip");
gfsFile.setId(id);
gfsFile.save();

You can load a file using one of the GridFS.find methods:

GridFSDBFile gfsFile = gfs.findOne(id);
InputStream in = gfsFile.getInputStream();
Sebastian
  • 16,813
  • 4
  • 49
  • 56
  • Thanks for the response. Can this approach also be used for documents which are less then 16 MB? I am not anticipating anything over 8 MB for my use case. – Obaid Maroof Mar 22 '16 at 11:48
  • 1
    Sure, it can be used for files of any size. – Sebastian Mar 22 '16 at 12:42
  • Thanks, sorry for continuously bugging. Probably I wasn't clear in my question, but I have got some more fields in my document as well along with the attachment file. Would it be possible to have some other fields in the same document? like name, subject, etc – Obaid Maroof Mar 22 '16 at 15:05
  • In general you should reference your file from your regular document using it's ID. If the data is more some kind of metadata of the file you can directly add it using `GridFSInputFile.setMetaData` – Sebastian Mar 22 '16 at 23:55