File tree Expand file tree Collapse file tree 1 file changed +55
-1
lines changed Expand file tree Collapse file tree 1 file changed +55
-1
lines changed Original file line number Diff line number Diff line change 66
77Encoding and decoding support for BSON in Rust
88
9+ ## Useful links
10+ - [ API Documentation] ( https://docs.rs/bson/ )
11+ - [ Serde] ( https://serde.rs/ )
12+
13+ ## Installation
14+ This crate works with Cargo and can be found on
15+ [ crates.io] ( https://crates.io/crates/bson ) with a ` Cargo.toml ` like:
16+
917``` toml
1018[dependencies ]
11- bson = " *"
19+ bson = " 0.3.2"
20+ ```
21+ ## Usage
22+ Link the library in _ main.rs_ :
23+ ``` rust
24+ #[macro_use(bson, doc)]
25+ extern crate bson;
26+ ```
27+
28+ Prepare your struct for Serde serialization:
29+ ``` rust
30+ #[derive(Serialize , Deserialize , Debug )]
31+ pub struct Person {
32+ #[serde(rename = " _id" )] // Use MongoDB's special primary key field name when serializing
33+ pub id : String ,
34+ pub name : String ,
35+ pub age : u32
36+ }
37+ ```
38+
39+ Serialize the struct:
40+ ``` rust
41+ use bson;
42+
43+ let person = Person {
44+ id : " 12345" ,
45+ name : " Emma" ,
46+ age : 3
47+ };
48+
49+ let serialized_person = bson :: to_bson (& person )? ; // Serialize
50+
51+ if let bson :: Bson :: Document (document ) = serialized_person {
52+ mongoCollection. insert_one (document , None )? ; // Insert into a MongoDB collection
53+ } else {
54+ println! (" Error converting the BSON object into a MongoDB document" );
55+ }
56+ ```
57+
58+ Deserialize the struct:
59+ ``` rust
60+ // Read the document from a MongoDB collection
61+ let person_document = mongoCollection. find_one (Some (doc! { " _id" => " 12345" }), None )?
62+ . expect (" Document not found" );
63+
64+ // Deserialize the document into a Person instance
65+ let person = bson :: from_bson (bson :: Bson :: Document (person_document ))?
1266```
You can’t perform that action at this time.
0 commit comments