Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving rust_decimal to mongodb

I'm trying to save a rust_decimal::Decimal object in MongoDB.

My first attempt was generally:

// self.db is of type mongodb::sync::Database

decimal = Decimal::new(1, 20);
let order = doc! {"decimal": decimal};
self.db.collection("collection").insert_one(order, None).unwrap();

Which yielded the error: the trait 'From<Decimal>' is not implemented for 'Bson'

This led me to learn about the bson crate. In its documentation I found about Decimal128, which Mongo supports, but it doesn't seem to have a convenient way to convert from either Decimal or String or anything really.

How do I insert the Decimal object to the document?

Crates versions:
mongodb 2.2.2
bson 2.3.0
rust_decimal 1.24.0

Edit: I've tried Decimal128::from_bytes(decimal.serialize()) but it turns 1 in Decimal to 4.294967296E-6167 in Decimal128 (little/big endian issue?).

like image 217
Dipsy Shrimp Avatar asked Mar 21 '26 04:03

Dipsy Shrimp


1 Answers

The documentation for Decimal128 explicitly states:

Currently, this type can only be used to round-trip through BSON. See RUST-36 to track the progress towards a complete implementation.

So it cannot be used for that.

Instead, I'd recommend you going through serde. rust_decimal supports serde (with various options and feature flags) and so does bson. You can serialize types into BSON with bson::ser::to_bson() or other functions in this module. For example:

decimal = Decimal::new(1, 20);
let order = doc! {"decimal": to_bson(&decimal).unwrap()};

By default this will serialize the decimal as a string, but you can customize that. See the docs for rust_decimal.

like image 96
Chayim Friedman Avatar answered Mar 22 '26 19:03

Chayim Friedman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!