Skip to content

Commit b516f7e

Browse files
committed
[#46] Linking to docs.rs from the README. Adding example snippets
1 parent 349db2d commit b516f7e

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

README.md

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,56 @@
66

77
Encoding 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]
1119
bson = "*"
1220
```
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+
```

0 commit comments

Comments
 (0)