Skip to content

Commit c9f363b

Browse files
authored
Merge branch 'MicrosoftDocs:main' into autovacuum-EC
2 parents 2441c2b + 1384ded commit c9f363b

3 files changed

Lines changed: 285 additions & 0 deletions

File tree

articles/documentdb/TOC.yml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,8 @@
4242
href: quickstart-java.md
4343
- name: Develop a Go console application
4444
href: quickstart-go.md
45+
- name: Develop a Rust console application
46+
href: quickstart-rust.md
4547
- name: Create a cluster using the Azure portal
4648
href: quickstart-portal.md
4749
- name: Deploy a cluster using Bicep templates

articles/documentdb/includes/selector-quickstart-dev.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,4 +11,5 @@ ms.date: 07/08/2025
1111
> - [C#](../quickstart-dotnet.md)
1212
> - [Java](../quickstart-java.md)
1313
> - [Go](../quickstart-go.md)
14+
> - [Rust](../quickstart-rust.md)
1415
>
Lines changed: 282 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,282 @@
1+
---
2+
title: Quickstart - Rust driver
3+
description: Learn how to use Azure DocumentDB (with MongoDB compatibility) to build NoSQL solutions using Rust. Start building applications today!
4+
author: seesharprun
5+
ms.author: sidandrews
6+
ms.topic: quickstart-sdk
7+
ms.devlang: rust
8+
ms.date: 10/14/2025
9+
ms.custom:
10+
- sfi-ropc-nochange
11+
ai-usage: ai-generated
12+
---
13+
14+
# Quickstart: Use Azure DocumentDB with MongoDB driver for Rust
15+
16+
[!INCLUDE[Developer Quickstart selector](includes/selector-quickstart-dev.md)]
17+
18+
In this quickstart, you create a basic Azure DocumentDB application using Rust. Azure DocumentDB is a NoSQL data store that allows applications to store documents in the cloud and access them using official MongoDB drivers. This guide shows how to create documents and perform basic tasks in your Azure DocumentDB cluster using Rust.
19+
20+
[API reference](https://docs.rs/mongodb/latest/mongodb/) | [Source code](https://github.com/mongodb/mongo-rust-driver) | [Package (crates.io)](https://crates.io/crates/mongodb)
21+
22+
## Prerequisites
23+
24+
[!INCLUDE[Prerequisites - Developer Quickstart](includes/prerequisite-quickstart-dev.md)]
25+
26+
- Rust 1.70 or later
27+
28+
## Create an Azure DocumentDB cluster
29+
30+
[!INCLUDE[Section - Create cluster](includes/section-create-cluster.md)]
31+
32+
## Get cluster credentials
33+
34+
[!INCLUDE[Section - Get credentials](includes/section-get-credentials.md)]
35+
36+
## Initialize the project
37+
38+
Create a new Rust project in your current directory.
39+
40+
1. Start in an empty directory.
41+
42+
1. Open a terminal in the current directory.
43+
44+
1. Create a new Rust project using Cargo.
45+
46+
```console
47+
cargo new azure-documentdb-rust-quickstart
48+
cd azure-documentdb-rust-quickstart
49+
```
50+
51+
### Install the client library
52+
53+
The client library is available through crates.io, as the `mongodb` crate.
54+
55+
1. Add the MongoDB Rust driver using Cargo.
56+
57+
```console
58+
cargo add mongodb
59+
```
60+
61+
1. Add the `tokio` runtime for async operations.
62+
63+
```console
64+
cargo add tokio --features full
65+
```
66+
67+
1. Add the `serde` crate for serialization support.
68+
69+
```console
70+
cargo add serde --features derive
71+
```
72+
73+
1. Add the `futures` crate for async stream operations.
74+
75+
```console
76+
cargo add futures
77+
```
78+
79+
1. Open the **src/main.rs** file for your application code.
80+
81+
1. Import the required modules into your application code:
82+
83+
```rust
84+
use futures::TryStreamExt;
85+
use mongodb::{
86+
bson::doc,
87+
options::ClientOptions,
88+
Client, Collection,
89+
};
90+
use serde::{Deserialize, Serialize};
91+
```
92+
93+
## Object model
94+
95+
| Name | Description |
96+
| --- | --- |
97+
| `Client` | Type used to connect to MongoDB. |
98+
| `Database` | Represents a database in the cluster. |
99+
| `Collection<T>` | Represents a collection within a database in the cluster. |
100+
101+
## Code examples
102+
103+
- [Authenticate the client](#authenticate-the-client)
104+
- [Get a collection](#get-a-collection)
105+
- [Create a document](#create-a-document)
106+
- [Retrieve a document](#retrieve-a-document)
107+
- [Query documents](#query-documents)
108+
109+
The code in this application connects to a database named `adventureworks` and a collection named `products`. The `products` collection contains details such as name, category, quantity, a unique identifier, and a sale flag for each product. The code samples here perform the most common operations when working with a collection.
110+
111+
### Authenticate the client
112+
113+
First, connect to the client using a basic connection string.
114+
115+
1. Create the main async function and set up the connection string. Replace `<your-cluster-name>`, `<your-username>`, and `<your-password>` with your actual cluster information.
116+
117+
```rust
118+
#[tokio::main]
119+
async fn main() -> Result<(), Box<dyn std::error::Error>> {
120+
// Connection string for Azure DocumentDB cluster
121+
let connection_string = "mongodb+srv://<your-username>:<your-password>@<your-cluster-name>.global.mongocluster.cosmos.azure.com/?tls=true&authMechanism=SCRAM-SHA-256&retrywrites=false&maxIdleTimeMS=120000";
122+
123+
// Parse connection string into client options
124+
let client_options = ClientOptions::parse(connection_string).await?;
125+
```
126+
127+
1. Create the MongoDB client and verify the connection.
128+
129+
```rust
130+
// Create a new client and connect to the server
131+
let client = Client::with_options(client_options)?;
132+
133+
// Ping the server to verify connection
134+
client
135+
.database("admin")
136+
.run_command(doc! { "ping": 1 })
137+
.await?;
138+
139+
println!("Successfully connected and pinged Azure DocumentDB");
140+
```
141+
142+
### Get a collection
143+
144+
Now, get your database and collection. If the database and collection doesn't already exist, use the driver to create it for you automatically.
145+
146+
1. Get a reference to the database.
147+
148+
```rust
149+
// Get database reference
150+
let database = client.database("adventureworks");
151+
println!("Connected to database: {}", database.name());
152+
```
153+
154+
1. Get a reference to the collection within the database.
155+
156+
```rust
157+
// Get collection reference
158+
let collection: Collection<Product> = database.collection("products");
159+
println!("Connected to collection: products");
160+
```
161+
162+
### Create a document
163+
164+
Then, create a couple of new documents within your collection. Upsert the documents to ensure that it replaces any existing documents if they already exist with the same unique identifier.
165+
166+
1. Define a Product struct and create sample product documents.
167+
168+
```rust
169+
// Define Product struct for type-safe operations
170+
#[derive(Debug, Serialize, Deserialize)]
171+
struct Product {
172+
#[serde(rename = "_id")]
173+
id: String,
174+
name: String,
175+
category: String,
176+
quantity: i32,
177+
price: f64,
178+
sale: bool,
179+
}
180+
181+
// Create sample products
182+
let products = vec![
183+
Product {
184+
id: "00000000-0000-0000-0000-000000004018".to_string(),
185+
name: "Windry Mittens".to_string(),
186+
category: "apparel-accessories-gloves-and-mittens".to_string(),
187+
quantity: 121,
188+
price: 35.00,
189+
sale: false,
190+
},
191+
Product {
192+
id: "00000000-0000-0000-0000-000000004318".to_string(),
193+
name: "Niborio Tent".to_string(),
194+
category: "gear-camp-tents".to_string(),
195+
quantity: 140,
196+
price: 420.00,
197+
sale: true,
198+
},
199+
];
200+
```
201+
202+
1. Insert the documents using upsert operations.
203+
204+
```rust
205+
// Insert documents with upsert
206+
for product in &products {
207+
let filter = doc! { "_id": &product.id };
208+
let update = doc! { "$set": mongodb::bson::to_document(product)? };
209+
210+
let result = collection
211+
.update_one(filter, update)
212+
.upsert(true)
213+
.await?;
214+
215+
if result.upserted_id.is_some() {
216+
println!("Inserted document with ID: {}", product.id);
217+
} else {
218+
println!("Updated document with ID: {}", product.id);
219+
}
220+
}
221+
```
222+
223+
### Retrieve a document
224+
225+
Next, perform a point read operation to retrieve a specific document from your collection.
226+
227+
1. Define the filter to find a specific document by ID.
228+
229+
```rust
230+
// Retrieve a specific document by ID
231+
let filter = doc! { "_id": "00000000-0000-0000-0000-000000004018" };
232+
```
233+
234+
1. Execute the query and retrieve the result.
235+
236+
```rust
237+
let retrieved_product = collection.find_one(filter).await?;
238+
239+
match retrieved_product {
240+
Some(product) => println!("Retrieved product: {} - ${:.2}", product.name, product.price),
241+
None => println!("Product not found"),
242+
}
243+
```
244+
245+
### Query documents
246+
247+
Finally, query multiple documents using the MongoDB Query Language (MQL).
248+
249+
1. Define a query to find documents matching specific criteria.
250+
251+
```rust
252+
// Query for products on sale
253+
let query_filter = doc! { "sale": true };
254+
let mut cursor = collection.find(query_filter).await?;
255+
```
256+
257+
1. Iterate through the cursor to retrieve all matching documents.
258+
259+
```rust
260+
println!("Products on sale:");
261+
while let Some(product) = cursor.try_next().await? {
262+
println!(
263+
"- {}: ${:.2} (Category: {})",
264+
product.name, product.price, product.category
265+
);
266+
}
267+
268+
Ok(())
269+
}
270+
```
271+
272+
## Explore your data using Visual Studio Code
273+
274+
[!INCLUDE[Section - Visual Studio Code extension](includes/section-quickstart-visual-studio-code-extension.md)]
275+
276+
## Clean up resources
277+
278+
[!INCLUDE[Section - Delete cluster](includes/section-delete-cluster.md)]
279+
280+
## Related content
281+
282+
- [What is Azure DocumentDB?](overview.md)

0 commit comments

Comments
 (0)