Home > OS >  How to convert a MongoDB RawDocumentBuf to a Rust struct?
How to convert a MongoDB RawDocumentBuf to a Rust struct?

Time:06-23

I am trying to use MongoDB rust driver with Rayon to make it faster. I know how to convert a RawDocumentBuf into a Document like this, which works really fast.

    let docs: Vec<RawDocumentBuf> = coll.find(None, None).await?.try_collect::<Vec<_>>().await?;

    let _y: Vec<Document> = docs.par_iter().map(|x| x.to_document().unwrap()).collect();

But I want a Rust struct, say Book, eventually. A Document can be converted into a struct, but I am not sure how to get a struct in the closure above.

let book: Book = bson::from_bson(Bson::Document(doc));

CodePudding user response:

You just missed another unwrap() after from_bson() at the end.

However you don't have to go via Document, you can deserialize from a RawDocumentBuf via bson::from_slice():

let docs: Vec<RawDocumentBuf> = coll.find(None, None).await?.try_collect().await?;

let books: Vec<Book> = docs
    .par_iter()
    .map(|raw| bson::from_slice(raw.as_bytes()).unwrap())
    .collect();
  • Related