File tree Expand file tree Collapse file tree 1 file changed +49
-0
lines changed Expand file tree Collapse file tree 1 file changed +49
-0
lines changed Original file line number Diff line number Diff line change 6
6
7
7
Encoding and decoding support for BSON in Rust
8
8
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
+
9
17
``` toml
10
18
[dependencies ]
11
19
bson = " *"
12
20
```
21
+ ## Usage
22
+
23
+ Prepare your struct for Serde serialization:
24
+ ``` rust
25
+ #[derive(Serialize , Deserialize , Debug )]
26
+ pub struct Person {
27
+ #[serde(rename = " _id" )] // Use MongoDB's special primary key field name when serializing
28
+ pub id : String ,
29
+ pub name : String ,
30
+ pub age : u32
31
+ }
32
+ ```
33
+
34
+ Serialize the struct:
35
+ ``` rust
36
+ use bson;
37
+
38
+ let person = Person {
39
+ id : " 12345" ,
40
+ name : " Emma" ,
41
+ age : 3
42
+ };
43
+
44
+ let serialized_person = bson :: to_bson (& person )? ; // Serialize
45
+
46
+ if let bson :: Bson :: Document (document ) = serialized {
47
+ mongoCollection. insert_one (document , None )? ; // Insert into a MongoDB collection
48
+ } else {
49
+ println! (" Error converting the BSON object into a MongoDB document" )
50
+ }
51
+ ```
52
+
53
+ Deserialize the struct:
54
+ ``` rust
55
+ // Read the document from a MongoDB collection
56
+ let person_document = mongoCollection. find_one (Some (doc! { " _id" => " 12345" }), None )?
57
+ . expect (" Document not found" )
58
+
59
+ // Deserialize the document into a Person instance
60
+ let person = bson :: from_bson (bson :: Bson :: Document (person_document ))?
61
+ ```
You can’t perform that action at this time.
0 commit comments