用Java将流写入mongoDB [英] Write stream into mongoDB in Java

查看:173
本文介绍了用Java将流写入mongoDB的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文件要存储在mongoDB中.我要避免加载整个文件(大小可能为几MB),而是要打开流并将其定向到mongoDB,以保持写入操作的性能.我不介意将内容存储在base64编码的byte []中.

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.

我目前正在将hibernate-ogm与Vertx服务器一起使用,但是如果它能有效地处理原因,我愿意切换到其他api.

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.

我想实际存储包含多个字段和多个附件的文档.

推荐答案

您可以使用 GridFS .尤其是当您需要存储较大的文件(> 16MB)时,建议使用以下方法:

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();

或者如果您有InputStream in:

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();

您可以使用GridFS.find方法之一加载文件:

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

GridFSDBFile gfsFile = gfs.findOne(id);
InputStream in = gfsFile.getInputStream();

这篇关于用Java将流写入mongoDB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆