#Introduction
This post details new upgrades in the Rust MongoDB Driver and BSON library to improve our integration with Serde. In the Rust Quick Start blog post, we discussed the trickiness of working with BSON, which has a dynamic schema, in Rust, which uses a static type system. The MongoDB Rust driver and BSON library use Serde to make the conversion between BSON and Rust structs and enums easier. In the 1.2.0 releases of these two libraries, we've included new Serde integration to make working directly with your own Rust data types more seamless and user-friendly.
#Prerequisites
This post assumes that you have a recent version of the Rust toolchain installed (v1.44+), and that you're comfortable with Rust syntax. It also assumes you're familiar with the Rust Serde library.
#Driver Changes
The 1.2.0 Rust driver release introduces a generic type parameter to the Collection type. The generic parameter represents the type of data you want to insert into and find from your MongoDB collection. Any Rust data type that derives/implements the Serde Serialize and Deserialize traits can be used as a type parameter for a Collection.
For example, I'm working with the following struct that defines the
schema of the data in my students
collection:
1 2 struct Student { 3 name: String, 4 grade: u32, 5 test_scores: Vec<u32>, 6 }
I can create a generic Collection
by using the
Database::collection_with_type method and
specifying Student
as the data type I'm working with.
1 let students: Collection<Student> = db.collection_with_type("students");
Prior to the introduction of the generic Collection
, the various CRUD
Collection
methods accepted and returned the
Document
type. This meant I would need to serialize my Student
structs to
Document