How to convert mongodb::Bson::Document to byte array (Vec<u8>) in Rust

Viewed 735

Im trying to send Bson Objects via Websocktes between c# and rust using this code to convert byte[] into mongodb::bson::Document in Rust.

if msg.is_binary() {
   let mut bin = std:::io::Cursor::new(msg.into_data());
   let doc = mongodb::bson::Document::from_reader(&mut bin); 
}

That works for a byte[] coming from c# MongoDB.Bson.ToBson()

but I wonder how to do the opposite. How would i convert mongodb::bson::Document into Vec byte array, so that i can parse it for example with: BsonDocument.ReadFrom() in c#.

Answer is:

let doc = doc! {"key": "value"};
let mut byte_array : Vec<u8> = vec![];
doc.to_writer(&mut byte_array);
/// byte_array is your BsonDocument as Vec<u8>
0 Answers
Related