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:

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

Leave a Reply