如何使用MongoDB Java Driver将Bson序列写入文件

use*_*220 9 java mongodb bson

使用MongoDB Java驱动程序库有一种方法可以将bson对象的写入流式传输到文件,然后再从该文件中流式读取bson对象.查看文档,我没有看到如何将一系列bson对象编码到类似于文件中具有一系列json对象的文件.

Yas*_*ash 2

MongoDB GridFS 是用于存储和检索文件的规范。

\n\n

使用GridFS存储文件 \xc2\xab GridFS 使用两个集合将文件保存到数据库:fs.files 和 fs.chunks。根据文件的大小,数据存储到多个单独的 \xe2\x80\x9ccunks\xe2\x80\x9d 中。\n * 使用 GridFS 的 MongoDB 文件。Refer to MyPost

\n\n

有关 GridFS 的更多信息,请访问我的Github wiki

\n\n\n\n
public static void main(String[] args) throws IOException {\n    mongoDB_GRIDFS("D:\\\\Yash\\\\JavaCSV.csv");\n}\npublic static void mongoDB_GRIDFS(String csvlocation) throws IOException{\n    Mongo Mongo = new Mongo( "localhost" , 27017 ); // Connect to MongoDB\n    DB db = Mongo.getDB( "DBName" ); // Get database\n    String bucketName = "BucketName";\n    GridFS gridFs = new GridFS(db,bucketName); //Create instance of GridFS implementation  \n    String imageName = "image1";\n    upload(gridFs, csvlocation, imageName);\n    download(gridFs, imageName);     \n    Mongo.close();\n}\npublic static void upload(GridFS gridFs, String csvlocation, String imageName) throws IOException{\n    GridFSInputFile gridFsInputFile = gridFs.createFile(new File(csvlocation));\n    gridFsInputFile.setId("777");\n    gridFsInputFile.setFilename(imageName); //Set a name on GridFS entry\n    gridFsInputFile.save(); //Save the file to MongoDB\n}\npublic static void download(GridFS gridFs, String imageName) throws IOException{\n    GridFSDBFile outputImageFile = gridFs.findOne(imageName);\n    String outcsvLocation = "D:\\\\Yash\\\\mongoCSV.csv";//Location of the file read from MongoDB to be written\n    outputImageFile.writeTo(new File(outcsvLocation));\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n\n\n

网格FS

\n\n
\n\n

CSV 文件到 JSON 对象和 JSON 字符串到 CSV 文件。

\n\n\n\n
\n\n

JSON 到 BSON 以及 BSON 到 JSON。

\n\n

MongoDB Java Driver jar附带了用于将 JSON 解析为 BSON 以及将 BSON 序列化为 JSON 的实用方法。

\n\n
    \n
  • BSON 库 \xc2\xab 一个独立的 BSON 库,具有新的编解码器基础设施,您可以使用它来构建高性能编码器和解码器,而无需中间 Map 实例。
  • \n
\n\n

例子

\n\n\n\n
DBObject dbObj = new Document("myKey", "myValue");\nString db_json = com.mongodb.util.JSON.serialize( dbObj );\n\nDBObject bson = ( DBObject ) com.mongodb.util.JSON.parse( jsonData );\nSystem.out.println("BSON Object : "+ bson);\n
Run Code Online (Sandbox Code Playgroud)\n\n\n\n

示例输出:

\n\n\n\n
BSON Object : [ { "Key2" : "21" , "Key1" : "11" } , { "Key2" : "22" , "Key1" : "12"}]\nJson : {"K1":"V1","K2":"V2"}\nMap : {K1=V1, K2=V2}\n
Run Code Online (Sandbox Code Playgroud)\n\n\n