如何使用MongoDB Java驱动程序将Bson序列写入文件

9
使用MongoDB Java驱动程序库,有没有一种方法将bson对象的写入流式传输到文件中,然后稍后从该文件流式传输bson对象的读取。查看文档,我没有看到关于如何对一系列bson对象进行编码以类似于在文件中具有一系列json对象的内容的说明。

这可能会有所帮助 https://jaihirsch.github.io/straw-in-a-haystack/mongodb/2014/09/16/generate-bson-files-with-java/ - Rajind Ruparathna
以及https://dev59.com/0Znga4cB1Zd3GeqPYm0V - Rajind Ruparathna
编写/读取bson对象是驱动程序已经完成的工作..它使用的文件是数据文件。Mongo是一个文档数据库,所有内容都是bson文档。因此,如果您有bson对象或一系列对象,并使用驱动程序,您可以将其持久化到db文件中。那么,数据库还有什么用处呢? - mcku
2个回答

2

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

使用GridFS来存储文件-GridFS使用两个集合将文件保存到数据库中:fs.files和fs.chunks。根据文件大小,数据被存储为多个单独的“块”。 * 使用GridFS存储MongoDB文件。请参阅我的帖子

有关GridFS的更多信息,请查看我的Github wiki

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

Grid FS


将CSV文件转换为JSON对象和JSON字符串转换为CSV文件。


将JSON转换为BSON和BSON转换为JSON。

MongoDB Java Driverjar带有用于解析JSON为BSON和序列化BSON为JSON的实用程序方法。

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

示例

DBObject dbObj = new Document("myKey", "myValue");
String db_json = com.mongodb.util.JSON.serialize( dbObj );

DBObject bson = ( DBObject ) com.mongodb.util.JSON.parse( jsonData );
System.out.println("BSON Object : "+ bson);

示例输出:

BSON Object : [ { "Key2" : "21" , "Key1" : "11" } , { "Key2" : "22" , "Key1" : "12"}]
Json : {"K1":"V1","K2":"V2"}
Map : {K1=V1, K2=V2}

你如何在Mongo shell中查看文件存储位置? - obesechicken13

1
根据MongoDb Java driver: BSON的文档,我编写了以下示例。这是您要寻找的内容吗?
逻辑类:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;

import org.apache.commons.io.IOUtils;
import org.bson.BsonBinaryReader;
import org.bson.BsonBinaryWriter;
import org.bson.BsonReader;
import org.bson.BsonWriter;
import org.bson.codecs.Codec;
import org.bson.codecs.DecoderContext;
import org.bson.codecs.EncoderContext;
import org.bson.codecs.StringCodec;
import org.bson.codecs.configuration.CodecRegistries;
import org.bson.codecs.configuration.CodecRegistry;
import org.bson.codecs.pojo.PojoCodecProvider;
import org.bson.io.BasicOutputBuffer;

public class Bson {

    FileOutputStream fop;
    FileInputStream fip;
    BsonWriter writer;
    BsonReader reader;
    Codec<Person> codec;
    EncoderContext ec;
    DecoderContext dc;
    BasicOutputBuffer output;

    public Bson() {
        PojoCodecProvider provider = PojoCodecProvider.builder()
                .register(Person.class)
                .build();

        CodecRegistry registry = CodecRegistries
                .fromRegistries(CodecRegistries.fromCodecs(new StringCodec()),
                        CodecRegistries.fromProviders(provider));
        codec = provider.get(Person.class, registry);
        ec = EncoderContext.builder().build();
        dc = DecoderContext.builder().build();
    }

    public static void main(String[] args) throws IOException {
        Bson bson = new Bson();
        // write data
        bson.initBsonWriter();
        bson.encodePerson(new Person("John", "Doe"));
        bson.encodePerson(new Person("John2", "Doe2"));
        bson.encodePerson(new Person("John3", "Doe3"));
        bson.closeFop();

        // read data
        bson.initBsonReader();
        Person person = bson.decodePerson();
        System.out.println(person);
        person = bson.decodePerson();
        System.out.println(person);
        person = bson.decodePerson();
        System.out.println(person);
        bson.closeFip();
    }

    public void initBsonWriter() throws IOException {
        openFop();
        output = new BasicOutputBuffer();
        writer = new BsonBinaryWriter(output);
        writer.writeStartDocument();
        writer.writeName("values");
        writer.writeStartArray();
    }

    public void initBsonReader() throws IOException {
        openFip();
        reader = new BsonBinaryReader(ByteBuffer.wrap(IOUtils.toByteArray(fip)));
        reader.readStartDocument();
        reader.readName();
        reader.readStartArray();
    }

    public void encodePerson(Person p) {
        codec.encode(writer, p, ec);
    }

    public Person decodePerson() {
        return codec.decode(reader, dc);
    }

    public void openFop() throws IOException {
        File file = new File("example.bson");
        fop = new FileOutputStream(file);

        // if file doesnt exists, then create it
        if (!file.exists()) {
            file.createNewFile();
        }
    }

    public void closeFop() throws IOException {
        writer.writeEndArray();
        writer.writeEndDocument();
        output.pipe(fop);
        fop.flush();
        fop.close();
    }

    public void openFip() throws IOException {
        File file = new File("example.bson");
        fip = new FileInputStream(file);
    }

    public void closeFip() throws IOException {
        fip.close();
    }
}

用于存储一些数据的POJO:

public class Person {
    private String firstName;
    private String lastName;

    public Person() { }

    public Person(final String firstName, final String lastName) {  
        this.firstName = firstName;
        this.lastName = lastName;}

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(final String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(final String lastName) {
        this.lastName = lastName;
    }

    @Override
    public String toString() {
        return "Person [firstName=" + firstName + ", lastName=" + lastName + "]";
    }
}

如果文件中写入了多个BSON对象,这是否有效? - user782220
我修改了这个例子。现在创建了一个包含Person对象数组的主文档文件。我使用了writer来创建主文档,这样你就可以轻松地将对象流到数组中。 - Adrian Farmadin
@user782220,现在我的示例支持将多个BSON对象流式传输到文件中,这是您要寻找的吗?还是我漏掉了什么? - Adrian Farmadin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接