You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
What version of MongoDB are you using? (Check with the MongoDB shell using db.version()) Not relevant
What is your MongoDB topology (standalone, replica set, sharded cluster, serverless)? Not relevant
Describe the bug
The following Foo struct can be serialized/deserialized to/from BSON using bson::to_document and bson::from_document. However, when using the mongodb crate it is not possible to deserialize such a value from a collection (serialization works).
tyilo
changed the title
Deserializing a document from a collection containing a HashMap with a new type struct key doesn't work
Deserializing a document from a collection containing a HashMap with a newtype struct key doesn't work
Apr 22, 2025
@tyilo thanks for this report! The discrepancy you're seeing is due to the way our raw BSON deserializer (which the driver uses under the hood) handles keys in maps. A simpler way to reproduce the issue is:
#[derive(Hash,PartialEq,Eq,Serialize,Deserialize)]structNewType(String);fnmain(){let map:HashMap<NewType,u64> = [(NewType("hi".to_string()),5)].into();let document = bson::to_document(&map).unwrap();let map_from_document:HashMap<NewType,u64> = bson::from_document(document).unwrap();// this succeedslet raw_document = bson::to_raw_document_buf(&map).unwrap();let map_from_raw_document:HashMap<NewType,u64> =
bson::from_slice(raw_document.as_bytes()).unwrap();// this panics when attempting to deserialize the string key}
Version 2.12 of bson included a refactor of the raw deserializer which updated the logic of the deserializer to use a BorrowedStrDeserializer for map keys -- apparently this doesn't play nicely with newtypes. A temporary workaround is to pin your bson version to 2.11 or earlier. You can also add the #[serde(transparent)] annotation to your newtype, which will allow for proper deserialization from a borrowed string.
I filed RUST-2205 to fix this issue; feel free to follow along there for updates.
Versions/Environment
cargo pkgid mongodb
&cargo pkgid bson
)db.version()
) Not relevantDescribe the bug
The following
Foo
struct can be serialized/deserialized to/from BSON usingbson::to_document
andbson::from_document
. However, when using themongodb
crate it is not possible to deserialize such a value from a collection (serialization works).The following code demonstrates the problem:
It fails with:
To Reproduce
Steps to reproduce the behavior:
MONGODB_URL
environment variable to a mongodb server URL.cargo test
The text was updated successfully, but these errors were encountered: