java语言中,读取mongodb数据库中的数据,并以json形式下载到本地。
这里给出数据库数据以及代码如下:
我这里的数据为嵌套形式,我的目的是想要下载configContent中的数据为json文件。
代码操作如下:(编写过程中,根据自己要读取并下载数据的需求,自行编写查询语句,只需在http响应数据代码那块中的content替换为你所查询出来要下载的数据,注意这里内容需从string转为 byte)
public HttpServletResponse getJsonFileById(String productKey, HttpServletResponse response, HttpServletRequest request) throws IOException {
if (StringUtils.isEmpty(productKey)){
throw new RuntimeException(ErrorCodeEnum.GL99990100.msg());
}
//查询嵌套文档
Document document = getChildDocuments(productKey);
Document model = (Document) document.get("configModel");
String content = JSONUtil.toJsonStr(model.get("configContent"));
//http相应数据
String fileName = document.get("productKey") + ".json";
response.reset();
response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
response.addHeader("Content-Length", "" + content.length());
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
toClient.write(content.getBytes(StandardCharsets.UTF_8), 0, content.length());
toClient.flush();
toClient.close();
return response;
}