Skip to content

Commit 94ad1e7

Browse files
authored
RUST-328 Update the README to include async examples (#172)
1 parent b69e2e1 commit 94ad1e7

File tree

1 file changed

+84
-18
lines changed

1 file changed

+84
-18
lines changed

README.md

Lines changed: 84 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,20 @@
11
# MongoDB Rust Driver
22
[![Crates.io](https://img.shields.io/crates/v/mongodb.svg)](https://crates.io/crates/mongodb) [![docs.rs](https://docs.rs/mongodb/badge.svg)](https://docs.rs/mongodb) [![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](LICENSE)
33

4-
This repository contains the officially supported MongoDB Rust driver, a client side library that can be used to interact with MongoDB deployments in Rust applications. It depends on the community-supported [`bson`](https://docs.rs/bson) library for BSON support.
4+
This repository contains the officially supported MongoDB Rust driver, a client side library that can be used to interact with MongoDB deployments in Rust applications. It depends on the [`bson`](https://docs.rs/bson) crate for BSON support. The driver contains a fully async API that supports either [`tokio`](https://crates.io/crates/tokio) (default) or [`async-std`](https://crates.io/crates/async-std), depending on the feature flags set. The driver also has a sync API that may be enabled via feature flag.
55

66
## Index
77
- [Installation](#Installation)
8+
- [Importing](#importing)
9+
- [Configuring the async runtime](#configuring-the-async-runtime)
10+
- [Enabling the sync API](#enabling-the-sync-api)
811
- [Example Usage](#example-usage)
9-
- [Connecting to a MongoDB deployment](#connecting-to-a-mongodb-deployment)
10-
- [Getting a handle to a database](#getting-a-handle-to-a-database)
11-
- [Inserting documents into a collection](#inserting-documents-into-a-collection)
12-
- [Finding documents in a collection](#finding-documents-in-a-collection)
12+
- [Using the async API](#using-the-async-api)
13+
- [Connecting to a MongoDB deployment](#connecting-to-a-mongodb-deployment)
14+
- [Getting a handle to a database](#getting-a-handle-to-a-database)
15+
- [Inserting documents into a collection](#inserting-documents-into-a-collection)
16+
- [Finding documents in a collection](#finding-documents-in-a-collection)
17+
- [Using the sync API](#using-the-sync-api)
1318
- [Bug Reporting / Feature Requests](#bug-reporting--feature-requests)
1419
- [Contributing](#contributing)
1520
- [Running the tests](#running-the-tests)
@@ -33,15 +38,38 @@ mongodb = "0.10.0"
3338
bson = "0.14.1"
3439
```
3540

41+
#### Configuring the async runtime
42+
The driver supports both of the most popular async runtime crates, namely [`tokio`](https://crates.io/crates/tokio) and [`async-std`](https://crates.io/crates/async-std). By default, the driver will use [`tokio`](https://crates.io/crates/tokio), but you can explicitly choose a runtime by specifying one of `"tokio-runtime"` or `"async-std-runtime"` feature flags in your `Cargo.toml`.
43+
44+
For example, to instruct the driver to work with [`async-std`](https://crates.io/crates/async-std), add the following to your `Cargo.toml`:
45+
```toml
46+
[dependencies.mongodb]
47+
version = "0.10.0"
48+
default-features = false
49+
features = ["async-std-runtime"]
50+
```
51+
52+
#### Enabling the sync API
53+
The driver also provides a blocking sync API. To enable this, add the `"sync"` feature to your `Cargo.toml`:
54+
```toml
55+
[dependencies.mongodb]
56+
version = "0.10.0"
57+
default-features = false
58+
features = ["sync"]
59+
```
60+
**Note:** if the sync API is enabled, the async-specific types will be privatized (e.g. `mongodb::Client`). The sync-specific types can be imported from `mongodb::sync` (e.g. `mongodb::sync::Client`).
61+
3662
## Example Usage
3763
Below are simple examples of using the driver. For more specific examples and the API reference, see the driver's [docs.rs page](https://docs.rs/mongodb).
38-
### Connecting to a MongoDB deployment
64+
65+
### Using the async API
66+
#### Connecting to a MongoDB deployment
3967
```rust
4068
use mongodb::{Client, options::ClientOptions};
4169
```
4270
```rust
4371
// Parse a connection string into an options struct.
44-
let mut client_options = ClientOptions::parse("mongodb://localhost:27017")?;
72+
let mut client_options = ClientOptions::parse("mongodb://localhost:27017").await?;
4573

4674
// Manually set an option.
4775
client_options.app_name = Some("My App".to_string());
@@ -50,23 +78,23 @@ client_options.app_name = Some("My App".to_string());
5078
let client = Client::with_options(client_options)?;
5179

5280
// List the names of the databases in that deployment.
53-
for db_name in client.list_database_names(None, None)? {
81+
for db_name in client.list_database_names(None, None).await? {
5482
println!("{}", db_name);
5583
}
5684
```
57-
### Getting a handle to a database
85+
#### Getting a handle to a database
5886
```rust
5987
// Get a handle to a database.
6088
let db = client.database("mydb");
6189

6290
// List the names of the collections in that database.
63-
for collection_name in db.list_collection_names(None)? {
91+
for collection_name in db.list_collection_names(None).await? {
6492
println!("{}", collection_name);
6593
}
6694
```
67-
### Inserting documents into a collection
95+
#### Inserting documents into a collection
6896
```rust
69-
use bson::{doc, bson};
97+
use bson::doc;
7098
```
7199
```rust
72100
// Get a handle to a collection in the database.
@@ -79,21 +107,22 @@ let docs = vec![
79107
];
80108

81109
// Insert some documents into the "mydb.books" collection.
82-
collection.insert_many(docs, None)?;
110+
collection.insert_many(docs, None).await?;
83111
```
84-
### Finding documents in a collection
112+
#### Finding documents in a collection
85113
```rust
86-
use bson::{doc, bson, Bson};
114+
use bson::{doc, Bson};
115+
use futures::stream::StreamExt;
87116
use mongodb::options::FindOptions;
88117
```
89118
```rust
90119
// Query the documents in the collection with a filter and an option.
91120
let filter = doc! { "author": "George Orwell" };
92121
let find_options = FindOptions::builder().sort(doc! { "title": 1 }).build();
93-
let cursor = collection.find(filter, find_options)?;
122+
let mut cursor = collection.find(filter, find_options).await?;
94123

95124
// Iterate over the results of the cursor.
96-
for result in cursor {
125+
while let Some(result) = cursor.next().await {
97126
match result {
98127
Ok(document) => {
99128
if let Some(title) = document.get("title").and_then(Bson::as_str) {
@@ -107,6 +136,43 @@ for result in cursor {
107136
}
108137
```
109138

139+
### Using the sync API
140+
The driver also provides a blocking sync API. See the [Installation](#enabling-the-sync-api) section for instructions on how to enable it.
141+
142+
The various sync-specific types are found in the `mongodb::sync` submodule rather than in the crate's top level like in the async API. The sync API calls through to the async API internally though, so it looks and behaves similarly to it.
143+
```rust
144+
use bson::{doc, Bson};
145+
use mongodb::sync::Client;
146+
```
147+
```rust
148+
let client = Client::with_uri_str("mongodb://localhost:27017")?;
149+
let database = client.database("mydb");
150+
let collection = database.collection("books");
151+
152+
let docs = vec![
153+
doc! { "title": "1984", "author": "George Orwell" },
154+
doc! { "title": "Animal Farm", "author": "George Orwell" },
155+
doc! { "title": "The Great Gatsby", "author": "F. Scott Fitzgerald" },
156+
];
157+
158+
// Insert some documents into the "mydb.books" collection.
159+
collection.insert_many(docs, None)?;
160+
161+
let cursor = collection.find(doc! { "author": "George Orwell" }, None)?;
162+
for result in cursor {
163+
match result {
164+
Ok(document) => {
165+
if let Some(title) = document.get("title").and_then(Bson::as_str) {
166+
println!("title: {}", title);
167+
} else {
168+
println!("no title found");
169+
}
170+
}
171+
Err(e) => return Err(e.into()),
172+
}
173+
}
174+
```
175+
110176
## Atlas note
111177

112178
Currently, the driver has issues connecting to Atlas tiers above M2 unless the server version is at least 4.2. We're working on fixing this, but in the meantime, a workaround is to upgrade your cluster to 4.2. The driver has no known issues with either M0 or M2 instances.
@@ -162,7 +228,7 @@ To run the tests with TLS/SSL enabled, you must enable it on the deployment and
162228
export MONGODB_URI="mongodb://localhost:27017/?tls=true&tlsCertificateKeyFile=cert.pem&tlsCAFile=ca.pem"
163229
cargo test --verbose
164230
```
165-
**Note:** When you open a pull request, your code will be run against a comprehensive testing matrix, so it is usually not necessary run the integration tests against all combinations of topology/auth/TLS locally.
231+
**Note:** When you open a pull request, your code will be run against a comprehensive testing matrix, so it is usually not necessary to run the integration tests against all combinations of topology/auth/TLS locally.
166232

167233
### Linter Tests
168234
Our linter tests use the nightly version of `rustfmt` to verify that the source is formatted properly and the stable version of `clippy` to statically detect any common mistakes.

0 commit comments

Comments
 (0)