Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to create a bson::Document from bson::raw::RawDocument in rust?

I’m trying to read from a bson file containing a single bson document (in reality I’d want to read from a byte array passed by the caller). The file was created from a python dict usign the RawBsonDocument class.

This is the code used to create the file:

import bson
from bson.raw_bson import RawBSONDocument

docs = []
docs.append(RawBSONDocument(bson.encode({'_id': 'SOME_ID_VALUE', 'a': 11111, 'b': 222222, 'c': {'x': None, 'y': 3333333}})))

with open("file.bson", 'wb') as fh:
    for doc in docs[:1]:
        fh.write(doc.raw)

Here’s my code so far:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

fn read_bson_file(){
    let mut f = File::open("file.bson").expect("no file found");

    let mut buffer = vec![];
    f.read_to_end(&mut buffer);

    println!("buffer size {}", buffer.len());

    let res = bson::raw::RawDocument::from_bytes(&buffer);

    let rawdoc = match res {
        Ok(raw) => raw,
        Err(err) => panic!("{:?}", err)
    };

}

how to convert the above rawdoc to the bson::Document type. Also, is there a way to directly create a bson::Document from the buffer I have above?

>Solution :

There’s an implementation of TryFrom<RawDocument> for bson::Document:

https://docs.rs/bson/latest/bson/struct.Document.html#impl-TryFrom%3C%26RawDocument%3E-for-Document

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading