<!DOCTYPE HTML>
<html lang="en" class="light" dir="ltr">
<head>
<!-- Book generated using mdBook -->
<meta charset="UTF-8">
<title>MongoDB Rust Driver</title>
<meta name="robots" content="noindex">
<!-- Custom HTML head -->
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#ffffff">
<link rel="icon" href="favicon.svg">
<link rel="shortcut icon" href="favicon.png">
<link rel="stylesheet" href="css/variables.css">
<link rel="stylesheet" href="css/general.css">
<link rel="stylesheet" href="css/chrome.css">
<link rel="stylesheet" href="css/print.css" media="print">
<!-- Fonts -->
<link rel="stylesheet" href="FontAwesome/css/font-awesome.css">
<link rel="stylesheet" href="fonts/fonts.css">
<!-- Highlight.js Stylesheets -->
<link rel="stylesheet" href="highlight.css">
<link rel="stylesheet" href="tomorrow-night.css">
<link rel="stylesheet" href="ayu-highlight.css">
<!-- Custom theme stylesheets -->
</head>
<body class="sidebar-visible no-js">
<div id="body-container">
<!-- Provide site root to javascript -->
<script>
var path_to_root = "";
var default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "navy" : "light";
</script>
<!-- Work around some values being stored in localStorage wrapped in quotes -->
<script>
try {
var theme = localStorage.getItem('mdbook-theme');
var sidebar = localStorage.getItem('mdbook-sidebar');
if (theme.startsWith('"') && theme.endsWith('"')) {
localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
}
if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
}
} catch (e) { }
</script>
<!-- Set the theme before any content is loaded, prevents flash -->
<script>
var theme;
try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
if (theme === null || theme === undefined) { theme = default_theme; }
var html = document.querySelector('html');
html.classList.remove('light')
html.classList.add(theme);
var body = document.querySelector('body');
body.classList.remove('no-js')
body.classList.add('js');
</script>
<input type="checkbox" id="sidebar-toggle-anchor" class="hidden">
<!-- Hide / unhide sidebar before it is displayed -->
<script>
var body = document.querySelector('body');
var sidebar = null;
var sidebar_toggle = document.getElementById("sidebar-toggle-anchor");
if (document.body.clientWidth >= 1080) {
try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
sidebar = sidebar || 'visible';
} else {
sidebar = 'hidden';
}
sidebar_toggle.checked = sidebar === 'visible';
body.classList.remove('sidebar-visible');
body.classList.add("sidebar-" + sidebar);
</script>
<nav id="sidebar" class="sidebar" aria-label="Table of contents">
<div class="sidebar-scrollbox">
<ol class="chapter"><li class="chapter-item expanded "><a href="index.html"><strong aria-hidden="true">1.</strong> Introduction</a></li><li class="chapter-item expanded "><a href="installation_features.html"><strong aria-hidden="true">2.</strong> Installation and Features</a></li><li class="chapter-item expanded "><a href="connecting.html"><strong aria-hidden="true">3.</strong> Connecting to the Database</a></li><li class="chapter-item expanded "><a href="reading.html"><strong aria-hidden="true">4.</strong> Reading From the Database</a></li><li class="chapter-item expanded "><div><strong aria-hidden="true">5.</strong> Writing To the Database</div></li><li class="chapter-item expanded "><a href="performance.html"><strong aria-hidden="true">6.</strong> Performance</a></li><li class="chapter-item expanded "><div><strong aria-hidden="true">7.</strong> Serde Integration</div></li><li class="chapter-item expanded "><div><strong aria-hidden="true">8.</strong> Sessions and Transactions</div></li><li class="chapter-item expanded "><div><strong aria-hidden="true">9.</strong> Change Streams</div></li><li class="chapter-item expanded "><div><strong aria-hidden="true">10.</strong> Monitoring</div></li><li class="chapter-item expanded "><a href="tracing.html"><strong aria-hidden="true">11.</strong> Tracing and Logging</a></li><li class="chapter-item expanded "><a href="web_framework_examples.html"><strong aria-hidden="true">12.</strong> Web Framework Examples</a></li><li class="chapter-item expanded "><a href="encryption.html"><strong aria-hidden="true">13.</strong> Encryption</a></li><li class="chapter-item expanded affix "><li class="part-title">Development</li><li class="chapter-item expanded "><div><strong aria-hidden="true">14.</strong> Writing Tests</div></li></ol>
</div>
<div id="sidebar-resize-handle" class="sidebar-resize-handle"></div>
</nav>
<!-- Track and set sidebar scroll position -->
<script>
var sidebarScrollbox = document.querySelector('#sidebar .sidebar-scrollbox');
sidebarScrollbox.addEventListener('click', function(e) {
if (e.target.tagName === 'A') {
sessionStorage.setItem('sidebar-scroll', sidebarScrollbox.scrollTop);
}
}, { passive: true });
var sidebarScrollTop = sessionStorage.getItem('sidebar-scroll');
sessionStorage.removeItem('sidebar-scroll');
if (sidebarScrollTop) {
// preserve sidebar scroll position when navigating via links within sidebar
sidebarScrollbox.scrollTop = sidebarScrollTop;
} else {
// scroll sidebar to current active section when navigating via "next/previous chapter" buttons
var activeSection = document.querySelector('#sidebar .active');
if (activeSection) {
activeSection.scrollIntoView({ block: 'center' });
}
}
</script>
<div id="page-wrapper" class="page-wrapper">
<div class="page">
<div id="menu-bar-hover-placeholder"></div>
<div id="menu-bar" class="menu-bar sticky">
<div class="left-buttons">
<label id="sidebar-toggle" class="icon-button" for="sidebar-toggle-anchor" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
<i class="fa fa-bars"></i>
</label>
<button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list">
<i class="fa fa-paint-brush"></i>
</button>
<ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu">
<li role="none"><button role="menuitem" class="theme" id="light">Light</button></li>
<li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li>
<li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li>
<li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li>
<li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li>
</ul>
<button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S" aria-controls="searchbar">
<i class="fa fa-search"></i>
</button>
</div>
<h1 class="menu-title">MongoDB Rust Driver</h1>
<div class="right-buttons">
<a href="print.html" title="Print this book" aria-label="Print this book">
<i id="print-button" class="fa fa-print"></i>
</a>
</div>
</div>
<div id="search-wrapper" class="hidden">
<form id="searchbar-outer" class="searchbar-outer">
<input type="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header">
</form>
<div id="searchresults-outer" class="searchresults-outer hidden">
<div id="searchresults-header" class="searchresults-header"></div>
<ul id="searchresults">
</ul>
</div>
</div>
<!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
<script>
document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
});
</script>
<div id="content" class="content">
<main>
<h1 id="introduction"><a class="header" href="#introduction">Introduction</a></h1>
<p><a href="https://crates.io/crates/mongodb"><img src="https://img.shields.io/crates/v/mongodb.svg" alt="Crates.io" /></a> <a href="https://docs.rs/mongodb"><img src="https://docs.rs/mongodb/badge.svg" alt="docs.rs" /></a> <a href="LICENSE"><img src="https://img.shields.io/badge/license-Apache%202.0-blue.svg" alt="License" /></a></p>
<p>This is the manual for the officially supported MongoDB Rust driver, a client side library that can be used to interact with MongoDB deployments in Rust applications. It uses the <a href="https://docs.rs/bson/latest"><code>bson</code></a> crate for BSON support. The driver contains a fully async API that supports either <a href="https://crates.io/crates/tokio"><code>tokio</code></a> (default) or <a href="https://crates.io/crates/async-std"><code>async-std</code></a>, depending on the feature flags set. The driver also has a sync API that may be enabled via feature flag.</p>
<h2 id="warning-about-timeouts--cancellation"><a class="header" href="#warning-about-timeouts--cancellation">Warning about timeouts / cancellation</a></h2>
<p>In async Rust, it is common to implement cancellation and timeouts by dropping a future after a certain period of time instead of polling it to completion. This is how <a href="https://docs.rs/tokio/latest/tokio/time/fn.timeout.html"><code>tokio::time::timeout</code></a> works, for example. However, doing this with futures returned by the driver can leave the driver's internals in an inconsistent state, which may lead to unpredictable or incorrect behavior (see <a href="https://jira.mongodb.org/browse/RUST-937">RUST-937</a> for more details). As such, it is <strong><em>highly</em></strong> recommended to poll all futures returned from the driver to completion. In order to still use timeout mechanisms like <code>tokio::time::timeout</code> with the driver, one option is to spawn tasks and time out on their <a href="https://docs.rs/tokio/latest/tokio/task/struct.JoinHandle.html"><code>JoinHandle</code></a> futures instead of on the driver's futures directly. This will ensure the driver's futures will always be completely polled while also allowing the application to continue in the event of a timeout.</p>
<p>e.g.</p>
<pre><pre class="playground"><code class="language-rust no_run edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span><span class="boring">extern crate mongodb;
</span><span class="boring">extern crate tokio;
</span><span class="boring">use std::time::Duration;
</span><span class="boring">use mongodb::{
</span><span class="boring"> Client,
</span><span class="boring"> bson::doc,
</span><span class="boring">};
</span><span class="boring">
</span><span class="boring">async fn foo() -> std::result::Result<(), Box<dyn std::error::Error>> {
</span><span class="boring">
</span><span class="boring">let client = Client::with_uri_str("mongodb://example.com").await?;
</span>let collection = client.database("foo").collection("bar");
let handle = tokio::task::spawn(async move {
collection.insert_one(doc! { "x": 1 }, None).await
});
tokio::time::timeout(Duration::from_secs(5), handle).await???;
<span class="boring">Ok(())
</span><span class="boring">}
</span><span class="boring">}</span></code></pre></pre>
<h2 id="minimum-supported-rust-version-msrv"><a class="header" href="#minimum-supported-rust-version-msrv">Minimum supported Rust version (MSRV)</a></h2>
<p>The MSRV for this crate is currently 1.61.0. This will rarely be increased, and if it ever is,
it will only happen in a minor or major version release.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="installation-and-features"><a class="header" href="#installation-and-features">Installation and Features</a></h1>
<h2 id="importing"><a class="header" href="#importing">Importing</a></h2>
<p>The driver is available on <a href="https://crates.io/crates/mongodb">crates.io</a>. To use the driver in your application, simply add it to your project's <code>Cargo.toml</code>.</p>
<pre><code class="language-toml">[dependencies]
mongodb = "2.1.0"
</code></pre>
<h2 id="configuring-the-async-runtime"><a class="header" href="#configuring-the-async-runtime">Configuring the async runtime</a></h2>
<p>The driver supports both of the most popular async runtime crates, namely <a href="https://crates.io/crates/tokio"><code>tokio</code></a> and <a href="https://crates.io/crates/async-std"><code>async-std</code></a>. By default, the driver will use <a href="https://crates.io/crates/tokio"><code>tokio</code></a>, but you can explicitly choose a runtime by specifying one of <code>"tokio-runtime"</code> or <code>"async-std-runtime"</code> feature flags in your <code>Cargo.toml</code>.</p>
<p>For example, to instruct the driver to work with <a href="https://crates.io/crates/async-std"><code>async-std</code></a>, add the following to your <code>Cargo.toml</code>:</p>
<pre><code class="language-toml">[dependencies.mongodb]
version = "2.7.0"
default-features = false
features = ["async-std-runtime"]
</code></pre>
<h2 id="enabling-the-sync-api"><a class="header" href="#enabling-the-sync-api">Enabling the sync API</a></h2>
<p>The driver also provides a blocking sync API. To enable this, add the <code>"sync"</code> or <code>"tokio-sync"</code> feature to your <code>Cargo.toml</code>:</p>
<pre><code class="language-toml">[dependencies.mongodb]
version = "2.7.0"
features = ["tokio-sync"]
</code></pre>
<p>Using the <code>"sync"</code> feature also requires using <code>default-features = false</code>.
<strong>Note:</strong> The sync-specific types can be imported from <code>mongodb::sync</code> (e.g. <code>mongodb::sync::Client</code>).</p>
<h2 id="all-feature-flags"><a class="header" href="#all-feature-flags">All Feature Flags</a></h2>
<div class="table-wrapper"><table><thead><tr><th style="text-align: left">Feature</th><th style="text-align: left">Description</th><th style="text-align: left">Extra dependencies</th><th style="text-align: left">Default</th></tr></thead><tbody>
<tr><td style="text-align: left"><code>tokio-runtime</code></td><td style="text-align: left">Enable support for the <code>tokio</code> async runtime</td><td style="text-align: left"><code>tokio</code> 1.0 with the <code>full</code> feature</td><td style="text-align: left">yes</td></tr>
<tr><td style="text-align: left"><code>async-std-runtime</code></td><td style="text-align: left">Enable support for the <code>async-std</code> runtime</td><td style="text-align: left"><code>async-std</code> 1.0</td><td style="text-align: left">no</td></tr>
<tr><td style="text-align: left"><code>sync</code></td><td style="text-align: left">Expose the synchronous API (<code>mongodb::sync</code>), using an async-std backend. Cannot be used with the <code>tokio-runtime</code> feature flag.</td><td style="text-align: left"><code>async-std</code> 1.0</td><td style="text-align: left">no</td></tr>
<tr><td style="text-align: left"><code>tokio-sync</code></td><td style="text-align: left">Expose the synchronous API (<code>mongodb::sync</code>), using a tokio backend. Cannot be used with the <code>async-std-runtime</code> feature flag.</td><td style="text-align: left"><code>tokio</code> 1.0 with the <code>full</code> feature</td><td style="text-align: left">no</td></tr>
<tr><td style="text-align: left"><code>aws-auth</code></td><td style="text-align: left">Enable support for the MONGODB-AWS authentication mechanism.</td><td style="text-align: left"><code>reqwest</code> 0.11</td><td style="text-align: left">no</td></tr>
<tr><td style="text-align: left"><code>bson-uuid-0_8</code></td><td style="text-align: left">Enable support for v0.8 of the <a href="docs.rs/uuid/0.8"><code>uuid</code></a> crate in the public API of the re-exported <code>bson</code> crate.</td><td style="text-align: left">n/a</td><td style="text-align: left">no</td></tr>
<tr><td style="text-align: left"><code>bson-uuid-1</code></td><td style="text-align: left">Enable support for v1.x of the <a href="docs.rs/uuid/1.0"><code>uuid</code></a> crate in the public API of the re-exported <code>bson</code> crate.</td><td style="text-align: left">n/a</td><td style="text-align: left">no</td></tr>
<tr><td style="text-align: left"><code>bson-chrono-0_4</code></td><td style="text-align: left">Enable support for v0.4 of the <a href="docs.rs/chrono/0.4"><code>chrono</code></a> crate in the public API of the re-exported <code>bson</code> crate.</td><td style="text-align: left">n/a</td><td style="text-align: left">no</td></tr>
<tr><td style="text-align: left"><code>bson-serde_with</code></td><td style="text-align: left">Enable support for the <a href="docs.rs/serde_with/latest"><code>serde_with</code></a> crate in the public API of the re-exported <code>bson</code> crate.</td><td style="text-align: left"><code>serde_with</code> 1.0</td><td style="text-align: left">no</td></tr>
<tr><td style="text-align: left"><code>zlib-compression</code></td><td style="text-align: left">Enable support for compressing messages with <a href="https://zlib.net/"><code>zlib</code></a></td><td style="text-align: left"><code>flate2</code> 1.0</td><td style="text-align: left">no</td></tr>
<tr><td style="text-align: left"><code>zstd-compression</code></td><td style="text-align: left">Enable support for compressing messages with <a href="http://facebook.github.io/zstd/"><code>zstd</code></a>. This flag requires Rust version 1.54.</td><td style="text-align: left"><code>zstd</code> 0.9.0</td><td style="text-align: left">no</td></tr>
<tr><td style="text-align: left"><code>snappy-compression</code></td><td style="text-align: left">Enable support for compressing messages with <a href="http://google.github.io/snappy/"><code>snappy</code></a></td><td style="text-align: left"><code>snap</code> 1.0.5</td><td style="text-align: left">no</td></tr>
<tr><td style="text-align: left"><code>openssl-tls</code></td><td style="text-align: left">Switch TLS connection handling to use <a href="https://docs.rs/openssl/0.10.38/">'openssl'</a>.</td><td style="text-align: left"><code>openssl</code> 0.10.38</td><td style="text-align: left">no</td></tr>
</tbody></table>
</div><div style="break-before: page; page-break-before: always;"></div><h1 id="connecting-to-the-database"><a class="header" href="#connecting-to-the-database">Connecting to the Database</a></h1>
<h2 id="connection-string"><a class="header" href="#connection-string">Connection String</a></h2>
<p>Connecting to a MongoDB database requires using a <a href="https://www.mongodb.com/docs/manual/reference/connection-string/#connection-string-formats">connection string</a>, a URI of the form:</p>
<pre><code class="language-uri">mongodb://[username:password@]host1[:port1][,...hostN[:portN]][/[defaultauthdb][?options]]
</code></pre>
<p>At its simplest this can just specify the host and port, e.g.</p>
<pre><code class="language-uri">mongodb://mongodb0.example.com:27017
</code></pre>
<p>For the full range of options supported by the Rust driver, see the documentation for the <a href="https://docs.rs/mongodb/latest/mongodb/options/struct.ClientOptions.html#method.parse"><code>ClientOptions::parse</code></a> method. That method will return a <a href="https://docs.rs/mongodb/latest/mongodb/options/struct.ClientOptions.html"><code>ClientOptions</code></a> struct, allowing for directly querying or setting any of the options supported by the Rust driver:</p>
<pre><pre class="playground"><code class="language-rust no_run edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span><span class="boring">extern crate mongodb;
</span><span class="boring">use mongodb::options::ClientOptions;
</span><span class="boring">async fn run() -> mongodb::error::Result<()> {
</span>let mut options = ClientOptions::parse("mongodb://mongodb0.example.com:27017").await?;
options.app_name = Some("My App".to_string());
<span class="boring">Ok(())
</span><span class="boring">}
</span><span class="boring">}</span></code></pre></pre>
<h2 id="creating-a-client"><a class="header" href="#creating-a-client">Creating a <code>Client</code></a></h2>
<p>The <a href="https://docs.rs/mongodb/latest/mongodb/struct.Client.html"><code>Client</code></a> struct is the main entry point for the driver. You can create one from a <code>ClientOptions</code> struct:</p>
<pre><pre class="playground"><code class="language-rust no_run edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span><span class="boring">extern crate mongodb;
</span><span class="boring">use mongodb::{Client, options::ClientOptions};
</span><span class="boring">async fn run() -> mongodb::error::Result<()> {
</span><span class="boring">let options = ClientOptions::parse("mongodb://mongodb0.example.com:27017").await?;
</span>let client = Client::with_options(options)?;
<span class="boring">Ok(())
</span><span class="boring">}
</span><span class="boring">}</span></code></pre></pre>
<p>As a convenience, if you don't need to modify the <code>ClientOptions</code> before creating the <code>Client</code>, you can directly create one from the connection string:</p>
<pre><pre class="playground"><code class="language-rust no_run edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span><span class="boring">extern crate mongodb;
</span><span class="boring">use mongodb::Client;
</span><span class="boring">async fn run() -> mongodb::error::Result<()> {
</span>let client = Client::with_uri_str("mongodb://mongodb0.example.com:27017").await?;
<span class="boring">Ok(())
</span><span class="boring">}
</span><span class="boring">}</span></code></pre></pre>
<p><code>Client</code> uses <a href="https://doc.rust-lang.org/std/sync/struct.Arc.html"><code>std::sync::Arc</code></a> internally, so it can safely be shared across threads or async tasks. For example:</p>
<pre><pre class="playground"><code class="language-rust no_run edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span><span class="boring">extern crate mongodb;
</span><span class="boring">extern crate tokio;
</span><span class="boring">use mongodb::{bson::Document, Client, error::Result};
</span><span class="boring">use tokio::task;
</span><span class="boring">
</span><span class="boring">async fn start_workers() -> Result<()> {
</span>let client = Client::with_uri_str("mongodb://example.com").await?;
for i in 0..5 {
let client_ref = client.clone();
task::spawn(async move {
let collection = client_ref.database("items").collection::<Document>(&format!("coll{}", i));
// Do something with the collection
});
}
<span class="boring">
</span><span class="boring">Ok(())
</span><span class="boring">}
</span><span class="boring">}</span></code></pre></pre>
<h2 id="client-performance"><a class="header" href="#client-performance">Client Performance</a></h2>
<p>While cloning a <code>Client</code> is very lightweight, creating a new one is an expensive operation. For most use cases, it is highly recommended to create a single <code>Client</code> and persist it for the lifetime of your application. For more information, see the <a href="performance.html">Performance</a> chapter.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="reading-from-the-database"><a class="header" href="#reading-from-the-database">Reading From the Database</a></h1>
<h2 id="database-and-collection-handles"><a class="header" href="#database-and-collection-handles">Database and Collection Handles</a></h2>
<p>Once you have a <code>Client</code>, you can call <a href="https://docs.rs/mongodb/latest/mongodb/struct.Client.html#method.database"><code>Client::database</code></a> to create a handle to a particular database on the server, and <a href="https://docs.rs/mongodb/latest/mongodb/struct.Database.html#method.collection"><code>Database::collection</code></a> to create a handle to a particular collection in that database. <a href="https://docs.rs/mongodb/latest/mongodb/struct.Database.html"><code>Database</code></a> and <a href="https://docs.rs/mongodb/latest/mongodb/struct.Collection.html"><code>Collection</code></a> handles are lightweight - creating them requires no IO, <code>clone</code>ing them is cheap, and they can be safely shared across threads or async tasks. For example:</p>
<pre><pre class="playground"><code class="language-rust no_run edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span><span class="boring">extern crate mongodb;
</span><span class="boring">extern crate tokio;
</span><span class="boring">use mongodb::{bson::Document, Client, error::Result};
</span><span class="boring">use tokio::task;
</span><span class="boring">
</span><span class="boring">async fn start_workers() -> Result<()> {
</span><span class="boring">let client = Client::with_uri_str("mongodb://example.com").await?;
</span>let db = client.database("items");
for i in 0..5 {
let db_ref = db.clone();
task::spawn(async move {
let collection = db_ref.collection::<Document>(&format!("coll{}", i));
// Do something with the collection
});
}
<span class="boring">
</span><span class="boring">Ok(())
</span><span class="boring">}
</span><span class="boring">}</span></code></pre></pre>
<p>A <code>Collection</code> can be parameterized with a type for the documents in the collection; this includes but is not limited to just <code>Document</code>. The various methods that accept instances of the documents (e.g. <a href="https://docs.rs/mongodb/latest/mongodb/struct.Collection.html#method.insert_one"><code>Collection::insert_one</code></a>) require that it implement the <code>Serialize</code> trait from the <a href="http://serde.rs/"><code>serde</code></a> crate. Similarly, the methods that return instances (e.g. <a href="https://docs.rs/mongodb/latest/mongodb/struct.Collection.html#method.find_one"><code>Collection::find_one</code></a>) require that it implement <code>Deserialize</code>.</p>
<p><code>Document</code> implements both and can always be used as the type parameter. However, it is recommended to define types that model your data which you can parameterize your <code>Collection</code>s with instead, since doing so eliminates a lot of boilerplate deserialization code and is often more performant.</p>
<pre><pre class="playground"><code class="language-rust no_run edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span><span class="boring">extern crate mongodb;
</span><span class="boring">extern crate tokio;
</span><span class="boring">extern crate serde;
</span><span class="boring">use mongodb::{
</span><span class="boring"> bson::doc,
</span><span class="boring"> error::Result,
</span><span class="boring">};
</span><span class="boring">use tokio::task;
</span><span class="boring">
</span><span class="boring">async fn start_workers() -> Result<()> {
</span><span class="boring">use mongodb::Client;
</span><span class="boring">
</span><span class="boring">let client = Client::with_uri_str("mongodb://example.com").await?;
</span>use serde::{Deserialize, Serialize};
// Define a type that models our data.
#[derive(Clone, Debug, Deserialize, Serialize)]
struct Item {
id: u32,
}
// Parameterize our collection with the model.
let coll = client.database("items").collection::<Item>("in_stock");
for i in 0..5 {
// Perform operations that work with directly our model.
coll.insert_one(Item { id: i }, None).await;
}
<span class="boring">
</span><span class="boring">Ok(())
</span><span class="boring">}
</span><span class="boring">}</span></code></pre></pre>
<p>For more information, see the <a href="serde_integration.html">Serde Integration</a> section.</p>
<h2 id="cursors"><a class="header" href="#cursors">Cursors</a></h2>
<p>Results from queries are generally returned via <a href="https://docs.rs/mongodb/latest/mongodb/struct.Cursor.html"><code>Cursor</code></a>, a struct which streams the results back from the server as requested. The <code>Cursor</code> type implements the <a href="https://docs.rs/futures/latest/futures/stream/trait.Stream.html"><code>Stream</code></a> trait from the <a href="https://crates.io/crates/futures"><code>futures</code></a> crate, and in order to access its streaming functionality you need to import at least one of the <a href="https://docs.rs/futures/latest/futures/stream/trait.StreamExt.html"><code>StreamExt</code></a> or <a href="https://docs.rs/futures/latest/futures/stream/trait.TryStreamExt.html"><code>TryStreamExt</code></a> traits.</p>
<pre><code class="language-toml"># In Cargo.toml, add the following dependency.
futures = "0.3"
</code></pre>
<pre><pre class="playground"><code class="language-rust no_run edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span><span class="boring">extern crate mongodb;
</span><span class="boring">extern crate serde;
</span><span class="boring">extern crate futures;
</span><span class="boring">use serde::Deserialize;
</span><span class="boring">#[derive(Deserialize)]
</span><span class="boring">struct Book { title: String }
</span><span class="boring">async fn foo() -> mongodb::error::Result<()> {
</span><span class="boring">let typed_collection = mongodb::Client::with_uri_str("").await?.database("").collection::<Book>("");
</span>// This trait is required to use `try_next()` on the cursor
use futures::stream::TryStreamExt;
use mongodb::{bson::doc, options::FindOptions};
// Query the books in the collection with a filter and an option.
let filter = doc! { "author": "George Orwell" };
let find_options = FindOptions::builder().sort(doc! { "title": 1 }).build();
let mut cursor = typed_collection.find(filter, find_options).await?;
// Iterate over the results of the cursor.
while let Some(book) = cursor.try_next().await? {
println!("title: {}", book.title);
}
<span class="boring">Ok(()) }
</span><span class="boring">}</span></code></pre></pre>
<p>If a <a href="https://docs.rs/mongodb/latest/mongodb/struct.Cursor.html"><code>Cursor</code></a> is still open when it goes out of scope, it will automatically be closed via an asynchronous <a href="https://www.mongodb.com/docs/manual/reference/command/killCursors/">killCursors</a> command executed from its <a href="https://doc.rust-lang.org/std/ops/trait.Drop.html"><code>Drop</code></a> implementation.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="performance"><a class="header" href="#performance">Performance</a></h1>
<h2 id="client-best-practices"><a class="header" href="#client-best-practices"><code>Client</code> Best Practices</a></h2>
<p>The <a href="https://docs.rs/mongodb/latest/mongodb/struct.Client.html"><code>Client</code></a> handles many aspects of database connection behind the scenes that can require manual management for other database drivers; it discovers server topology, monitors it for any changes, and maintains an internal connection pool. This has implications for how a <code>Client</code> should be used for best performance.</p>
<h3 id="lifetime"><a class="header" href="#lifetime">Lifetime</a></h3>
<p>A <code>Client</code> should be as long-lived as possible. Establishing a new <code>Client</code> is relatively slow and resource-intensive, so ideally that should only be done once at application startup. Because <code>Client</code> is implemented using an internal <a href="https://doc.rust-lang.org/std/sync/struct.Arc.html"><code>Arc</code></a>, it can safely be shared across threads or tasks, and <code>clone</code>ing it to pass to new contexts is extremely cheap.</p>
<pre><pre class="playground"><code class="language-rust no_run edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span><span class="boring">extern crate mongodb;
</span><span class="boring">use mongodb::Client;
</span><span class="boring">use std::error::Error;
</span>// This will be very slow because it's constructing and tearing down a `Client`
// with every request.
async fn handle_request_bad() -> Result<(), Box<dyn Error>> {
let client = Client::with_uri_str("mongodb://example.com").await?;
// Do something with the client
Ok(())
}
// This will be much faster.
async fn handle_request_good(client: &Client) -> Result<(), Box<dyn Error>> {
// Do something with the client
Ok(())
}
<span class="boring">}</span></code></pre></pre>
<p>This is especially noticeable when using a framework that provides connection pooling; because <code>Client</code> does its own pooling internally, attempting to maintain a pool of <code>Client</code>s will (somewhat counter-intuitively) result in worse performance than using a single one.</p>
<h3 id="runtime"><a class="header" href="#runtime">Runtime</a></h3>
<p>A <code>Client</code> is implicitly bound to the instance of the <code>tokio</code> or <code>async-std</code> runtime in which it was created. Attempting to execute operations on a different runtime instance will cause incorrect behavior and unpredictable failures. This is easy to accidentally invoke when testing, as the <code>tokio::test</code> or <code>async_std::test</code> helper macros create a new runtime for each test.</p>
<pre><pre class="playground"><code class="language-rust no_run edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span><span class="boring">extern crate mongodb;
</span><span class="boring">extern crate once_cell;
</span><span class="boring">extern crate tokio;
</span><span class="boring">use mongodb::Client;
</span><span class="boring">use std::error::Error;
</span>use tokio::runtime::Runtime;
use once_cell::sync::Lazy;
static CLIENT: Lazy<Client> = Lazy::new(|| {
let rt = Runtime::new().unwrap();
rt.block_on(async {
Client::with_uri_str("mongodb://example.com").await.unwrap()
})
});
// This will inconsistently fail.
#[tokio::test]
async fn test_list_dbs() -> Result<(), Box<dyn Error>> {
CLIENT.list_database_names(None, None).await?;
Ok(())
}
<span class="boring">}</span></code></pre></pre>
<p>To work around this issue, either create a new <code>Client</code> for every async test, or bundle the <code>Runtime</code> along with the client and don't use the test helper macros.</p>
<pre><pre class="playground"><code class="language-rust no_run edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span><span class="boring">extern crate mongodb;
</span><span class="boring">extern crate once_cell;
</span><span class="boring">extern crate tokio;
</span><span class="boring">use mongodb::Client;
</span><span class="boring">use std::error::Error;
</span>use tokio::runtime::Runtime;
use once_cell::sync::Lazy;
static CLIENT_RUNTIME: Lazy<(Client, Runtime)> = Lazy::new(|| {
let rt = Runtime::new().unwrap();
let client = rt.block_on(async {
Client::with_uri_str("mongodb://example.com").await.unwrap()
});
(client, rt)
});
#[test]
fn test_list_dbs() -> Result<(), Box<dyn Error>> {
let (client, rt) = &*CLIENT_RUNTIME;
rt.block_on(async {
client.list_database_names(None, None).await
})?;
Ok(())
}
<span class="boring">}</span></code></pre></pre>
<p>or</p>
<pre><pre class="playground"><code class="language-rust no_run edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span><span class="boring">extern crate mongodb;
</span><span class="boring">extern crate tokio;
</span><span class="boring">use mongodb::Client;
</span><span class="boring">use std::error::Error;
</span>#[tokio::test]
async fn test_list_dbs() -> Result<(), Box<dyn Error>> {
let client = Client::with_uri_str("mongodb://example.com").await?;
CLIENT.list_database_names(None, None).await?;
Ok(())
}
<span class="boring">}</span></code></pre></pre>
<h2 id="parallelism"><a class="header" href="#parallelism">Parallelism</a></h2>
<p>Where data operations are naturally parallelizable, spawning many asynchronous tasks that use the driver concurrently is often the best way to achieve maximum performance, as the driver is designed to work well in such situations.</p>
<pre><pre class="playground"><code class="language-rust no_run edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span><span class="boring">extern crate mongodb;
</span><span class="boring">extern crate tokio;
</span><span class="boring">use mongodb::{bson::Document, Client, error::Result};
</span><span class="boring">use tokio::task;
</span><span class="boring">
</span><span class="boring">async fn start_workers() -> Result<()> {
</span>let client = Client::with_uri_str("mongodb://example.com").await?;
for i in 0..5 {
let client_ref = client.clone();
task::spawn(async move {
let collection = client_ref.database("items").collection::<Document>(&format!("coll{}", i));
// Do something with the collection
});
}
<span class="boring">
</span><span class="boring">Ok(())
</span><span class="boring">}
</span><span class="boring">}</span></code></pre></pre>
<div style="break-before: page; page-break-before: always;"></div><h1 id="tracing-and-logging"><a class="header" href="#tracing-and-logging">Tracing and Logging</a></h1>
<p>The driver utilizes the <a href="https://crates.io/crates/tracing"><code>tracing</code></a> crate to emit events at points of interest. To enable this, you must turn on the <code>tracing-unstable</code> feature flag.</p>
<h2 id="stability-guarantees"><a class="header" href="#stability-guarantees">Stability Guarantees</a></h2>
<p>This functionality is considered unstable as the <code>tracing</code> crate has not reached 1.0 yet. Future minor versions of the driver may upgrade the <code>tracing</code> dependency
to a new version which is not backwards-compatible with <code>Subscriber</code>s that depend on older versions of <code>tracing</code>.
Additionally, future minor releases may make changes such as:</p>
<ul>
<li>add or remove tracing events</li>
<li>add or remove values attached to tracing events</li>
<li>change the types and/or names of values attached to tracing events</li>
<li>add or remove driver-defined tracing spans</li>
<li>change the severity level of tracing events</li>
</ul>
<p>Such changes will be called out in release notes.</p>
<h2 id="event-targets"><a class="header" href="#event-targets">Event Targets</a></h2>
<p>Currently, events are emitted under the following targets:</p>
<div class="table-wrapper"><table><thead><tr><th>Target</th><th>Description</th></tr></thead><tbody>
<tr><td><code>mongodb::command</code></td><td>Events describing commands sent to the database and their success or failure.</td></tr>
<tr><td><code>mongodb::server_selection</code></td><td>Events describing the driver's process of selecting a server in the database deployment to send a command to.</td></tr>
<tr><td><code>mongodb::connection</code></td><td>Events describing the behavior of driver connection pools and the connections they contain.</td></tr>
</tbody></table>
</div>
<h2 id="consuming-events"><a class="header" href="#consuming-events">Consuming Events</a></h2>
<p>To consume events in your application, in addition to enabling the <code>tracing-unstable</code> feature flag, you must either register a <code>tracing</code>-compatible subscriber or a <code>log</code>-compatible logger, as detailed in the following sections.</p>
<h3 id="consuming-events-with-tracing"><a class="header" href="#consuming-events-with-tracing">Consuming Events with <code>tracing</code></a></h3>
<p>To consume events with <code>tracing</code>, you will need to register a type implementing the <code>tracing::Subscriber</code> trait in your application, as <a href="https://docs.rs/tracing/latest/tracing/#in-executables">discussed in the <code>tracing</code> docs</a>.</p>
<p>Here's a minimal example of a program using the driver which uses a tracing subscriber.</p>
<p>First, add the following to <code>Cargo.toml</code>:</p>
<pre><code class="language-toml no_run">tracing = "LATEST_VERSION_HERE"
tracing-subscriber = "LATEST_VERSION_HERE"
mongodb = { version = "LATEST_VERSION_HERE", features = ["tracing-unstable"] }
</code></pre>
<p>And then in <code>main.rs</code>:</p>
<pre><pre class="playground"><code class="language-rust no_run edition2021"><span class="boring">extern crate mongodb;
</span><span class="boring">extern crate tokio;
</span><span class="boring">extern crate tracing_subscriber;
</span><span class="boring">use std::env;
</span>use mongodb::{bson::doc, error::Result, Client};
#[tokio::main]
async fn main() -> Result<()> {
// Register a global tracing subscriber which will obey the RUST_LOG environment variable
// config.
tracing_subscriber::fmt::init();
// Create a MongoDB client.
let mongodb_uri =
env::var("MONGODB_URI").expect("The MONGODB_URI environment variable was not set.");
let client = Client::with_uri_str(mongodb_uri).await?;
// Insert a document.
let coll = client.database("test").collection("test_coll");
coll.insert_one(doc! { "x" : 1 }, None).await?;
Ok(())
}</code></pre></pre>
<p>This program can be run from the command line as follows, using the <a href="https://docs.rs/tracing-subscriber/0.3.16/tracing_subscriber/fmt/index.html#filtering-events-with-environment-variables"><code>RUST_LOG</code></a> environment variable to configure verbosity levels and observe command-related events with severity debug or higher:</p>
<pre><code class="language-sh no_run">RUST_LOG='mongodb::command=debug' MONGODB_URI='YOUR_URI_HERE' cargo run
</code></pre>
<p>The output will look something like the following:</p>
<pre><code class="language-text">2023-02-03T19:20:16.091822Z DEBUG mongodb::command: Command started topologyId="63dd5e706af9908fc834fd94" command="{\"insert\":\"test_coll\",\"ordered\":true,\"$db\":\"test\",\"lsid\":{\"id\":{\"$binary\":{\"base64\":\"y/v7PiLaRwOhT0RBFRDtNw==\",\"subType\":\"04\"}}},\"documents\":[{\"_id\":{\"$oid\":\"63dd5e706af9908fc834fd95\"},\"x\":1}]}" databaseName="test" commandName="insert" requestId=4 driverConnectionId=1 serverConnectionId=16 serverHost="localhost" serverPort=27017
2023-02-03T19:20:16.092700Z DEBUG mongodb::command: Command succeeded topologyId="63dd5e706af9908fc834fd94" reply="{\"n\":1,\"ok\":1.0}" commandName="insert" requestId=4 driverConnectionId=1 serverConnectionId=16 serverHost="localhost" serverPort=27017 durationMS=0
</code></pre>
<h3 id="consuming-events-with-log"><a class="header" href="#consuming-events-with-log">Consuming Events with <code>log</code></a></h3>
<p>Alternatively, to consume events with <code>log</code>, you will need to add <code>tracing</code> as a dependency of your application, and enable either its <code>log</code> or <code>log-always</code> feature.
Those features are described in detail <a href="https://docs.rs/tracing/latest/tracing/#log-compatibility">here</a>. </p>
<p>Here's a minimal example of a program using the driver which uses <a href="https://crates.io/crates/env_logger"><code>env_logger</code></a>.</p>
<p>In <code>Cargo.toml</code>:</p>
<pre><code class="language-toml no_run">tracing = { version = "LATEST_VERSION_HERE", features = ["log"] }
mongodb = { version = "LATEST_VERSION_HERE", features = ["tracing-unstable"] }
env_logger = "LATEST_VERSION_HERE"
</code></pre>
<p>And in <code>main.rs</code>:</p>
<pre><pre class="playground"><code class="language-rust no_run edition2021"><span class="boring">extern crate mongodb;
</span><span class="boring">extern crate tokio;
</span><span class="boring">extern crate env_logger;
</span>use std::env;
use mongodb::{bson::doc, error::Result, Client};
#[tokio::main]
async fn main() -> Result<()> {
// Register a global logger.
env_logger::init();
// Create a MongoDB client.
let mongodb_uri =
env::var("MONGODB_URI").expect("The MONGODB_URI environment variable was not set.");
let client = Client::with_uri_str(mongodb_uri).await?;
// Insert a document.
let coll = client.database("test").collection("test_coll");
coll.insert_one(doc! { "x" : 1 }, None).await?;
Ok(())
}</code></pre></pre>
<p>This program can be run from the command line as follows, using the <a href="https://docs.rs/env_logger/latest/env_logger/#enabling-logging"><code>RUST_LOG</code></a> environment variable to configure verbosity levels and observe command-related messages with severity debug or higher:</p>
<pre><code class="language-sh no_run">RUST_LOG='mongodb::command=debug' MONGODB_URI='YOUR_URI_HERE' cargo run
</code></pre>
<p>The output will look something like the following:</p>
<pre><code class="language-text">2023-02-03T19:20:16.091822Z DEBUG mongodb::command: Command started topologyId="63dd5e706af9908fc834fd94" command="{\"insert\":\"test_coll\",\"ordered\":true,\"$db\":\"test\",\"lsid\":{\"id\":{\"$binary\":{\"base64\":\"y/v7PiLaRwOhT0RBFRDtNw==\",\"subType\":\"04\"}}},\"documents\":[{\"_id\":{\"$oid\":\"63dd5e706af9908fc834fd95\"},\"x\":1}]}" databaseName="test" commandName="insert" requestId=4 driverConnectionId=1 serverConnectionId=16 serverHost="localhost" serverPort=27017
2023-02-03T19:20:16.092700Z DEBUG mongodb::command: Command succeeded topologyId="63dd5e706af9908fc834fd94" reply="{\"n\":1,\"ok\":1.0}" commandName="insert" requestId=4 driverConnectionId=1 serverConnectionId=16 serverHost="localhost" serverPort=27017 durationMS=0
</code></pre>
<div style="break-before: page; page-break-before: always;"></div><h1 id="web-framework-examples"><a class="header" href="#web-framework-examples">Web Framework Examples</a></h1>
<h2 id="actix"><a class="header" href="#actix">Actix</a></h2>
<p>The driver can be used easily with the Actix web framework by storing a <code>Client</code> in Actix application data. A full example application for using MongoDB with Actix can be found <a href="https://github.com/actix/examples/tree/master/databases/mongodb">here</a>.</p>
<h2 id="rocket"><a class="header" href="#rocket">Rocket</a></h2>
<p>The Rocket web framework provides built-in support for MongoDB via the Rust driver. The documentation for the <a href="https://api.rocket.rs/v0.5-rc/rocket_db_pools/index.html"><code>rocket_db_pools</code></a> crate contains instructions for using MongoDB with your Rocket application.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="unstable-api"><a class="header" href="#unstable-api">Unstable API</a></h1>
<p>To enable support for in-use encryption (<a href="https://www.mongodb.com/docs/manual/core/csfle/">client-side field level encryption</a> and <a href="https://www.mongodb.com/docs/manual/core/queryable-encryption/">queryable encryption</a>), enable the <code>"in-use-encryption-unstable"</code> feature of the <code>mongodb</code> crate. As the name implies, the API for this feature is unstable, and may change in backwards-incompatible ways in minor releases.</p>
<h1 id="client-side-field-level-encryption"><a class="header" href="#client-side-field-level-encryption">Client-Side Field Level Encryption</a></h1>
<p>Starting with MongoDB 4.2, client-side field level encryption allows an application to encrypt specific data fields in addition to pre-existing MongoDB encryption features such as <a href="https://dochub.mongodb.org/core/security-encryption-at-rest">Encryption at Rest</a> and <a href="https://dochub.mongodb.org/core/security-tls-transport-encryption">TLS/SSL (Transport Encryption)</a>.</p>
<p>With field level encryption, applications can encrypt fields in documents prior to transmitting data over the wire to the server. Client-side field level encryption supports workloads where applications must guarantee that unauthorized parties, including server administrators, cannot read the encrypted data.</p>
<p>See also the MongoDB documentation on <a href="https://dochub.mongodb.org/core/client-side-field-level-encryption">Client Side Field Level Encryption</a>.</p>
<h2 id="dependencies"><a class="header" href="#dependencies">Dependencies</a></h2>
<p>To get started using client-side field level encryption in your project, you will need to install <a href="https://github.com/mongodb/libmongocrypt">libmongocrypt</a>, which can be fetched from a <a href="https://www.mongodb.com/docs/manual/core/csfle/reference/libmongocrypt/#std-label-csfle-reference-libmongocrypt">variety of package repositories</a>. If you install libmongocrypt in a location outside of the system library search path, the <code>MONGOCRYPT_LIB_DIR</code> environment variable will need to be set when compiling your project.</p>
<p>Additionally, either <code>crypt_shared</code> or <code>mongocryptd</code> are required in order to use automatic client-side encryption.</p>
<h3 id="crypt_shared"><a class="header" href="#crypt_shared">crypt_shared</a></h3>
<p>The Automatic Encryption Shared Library (crypt_shared) provides the same functionality as mongocryptd, but does not require you to spawn another process to perform automatic encryption.</p>
<p>By default, the <code>mongodb</code> crate attempts to load crypt_shared from the system and if found uses it automatically. To load crypt_shared from another location, set the <code>"cryptSharedLibPath"</code> field in <code>extra_options</code>:</p>
<pre><pre class="playground"><code class="language-rust no_run edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span><span class="boring">extern crate mongodb;
</span><span class="boring">use mongodb::{bson::doc, Client, error::Result};
</span><span class="boring">
</span><span class="boring">async fn func() -> Result<()> {
</span><span class="boring">let options = todo!();
</span><span class="boring">let kv_namespace = todo!();
</span><span class="boring">let kms_providers: Vec<_> = todo!();
</span>let client = Client::encrypted_builder(options, kv_namespace, kms_providers)?
.extra_options(doc! {
"cryptSharedLibPath": "/path/to/crypt/shared",
})
.build();
<span class="boring">
</span><span class="boring">Ok(())
</span><span class="boring">}
</span><span class="boring">}</span></code></pre></pre>
<p>If the <code>mongodb</code> crate cannot load crypt_shared it will attempt to fallback to using mongocryptd by default. Include <code>"cryptSharedRequired": true</code> in the <code>extra_options</code> document to always use crypt_shared and fail if it could not be loaded.</p>
<p>For detailed installation instructions see the <a href="https://www.mongodb.com/docs/manual/core/queryable-encryption/reference/shared-library">MongoDB documentation on Automatic Encryption Shared Library</a>.</p>
<h3 id="mongocryptd"><a class="header" href="#mongocryptd">mongocryptd</a></h3>
<p>If using <code>crypt_shared</code> is not an option, the <code>mongocryptd</code> binary is required for automatic client-side encryption and is included as a component in the <a href="https://dochub.mongodb.org/core/install-mongodb-enterprise">MongoDB Enterprise Server package</a>. For detailed installation instructions see the <a href="https://dochub.mongodb.org/core/client-side-field-level-encryption-mongocryptd">MongoDB documentation on mongocryptd</a>.</p>
<p><code>mongocryptd</code> performs the following:</p>
<ul>
<li>Parses the automatic encryption rules specified to the database connection. If the JSON schema contains invalid automatic encryption syntax or any document validation syntax, <code>mongocryptd</code> returns an error.</li>
<li>Uses the specified automatic encryption rules to mark fields in read and write operations for encryption.</li>
<li>Rejects read/write operations that may return unexpected or incorrect results when applied to an encrypted field. For supported and unsupported operations, see <a href="https://dochub.mongodb.org/core/client-side-field-level-encryption-read-write-support">Read/Write Support with Automatic Field Level Encryption</a>.</li>
</ul>
<p>A <code>Client</code> configured with auto encryption will automatically spawn the <code>mongocryptd</code> process from the application's <code>PATH</code>. Applications can control the spawning behavior as part of the automatic encryption options:</p>
<pre><pre class="playground"><code class="language-rust no_run edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span><span class="boring">extern crate mongodb;
</span><span class="boring">use mongodb::{bson::doc, Client, error::Result};
</span><span class="boring">
</span><span class="boring">async fn func() -> Result<()> {
</span><span class="boring">let options = todo!();
</span><span class="boring">let kv_namespace = todo!();
</span><span class="boring">let kms_providers: Vec<_> = todo!();
</span>let client = Client::encrypted_builder(options, kv_namespace, kms_providers)?
.extra_options(doc! {
"mongocryptdSpawnPath": "/path/to/mongocryptd",
"mongocryptdSpawnArgs": ["--logpath=/path/to/mongocryptd.log", "--logappend"],
})
.build();
<span class="boring">
</span><span class="boring">Ok(())
</span><span class="boring">}
</span><span class="boring">}</span></code></pre></pre>
<p>If your application wishes to manage the <code>mongocryptd</code> process manually, it is possible to disable spawning <code>mongocryptd</code>:</p>
<pre><pre class="playground"><code class="language-rust no_run edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span><span class="boring">extern crate mongodb;
</span><span class="boring">use mongodb::{bson::doc, Client, error::Result};
</span><span class="boring">
</span><span class="boring">async fn func() -> Result<()> {
</span><span class="boring">let options = todo!();
</span><span class="boring">let kv_namespace = todo!();
</span><span class="boring">let kms_providers: Vec<_> = todo!();
</span>let client = Client::encrypted_builder(options, kv_namespace, kms_providers)?
.extra_options(doc! {
"mongocryptdBypassSpawn": true,
"mongocryptdURI": "mongodb://localhost:27020",
})
.build();
<span class="boring">
</span><span class="boring">Ok(())
</span><span class="boring">}
</span><span class="boring">}</span></code></pre></pre>
<p><code>mongocryptd</code> is only responsible for supporting automatic client-side field level encryption and does not itself perform any encryption or decryption.</p>
<h2 id="automatic-client-side-field-level-encryption"><a class="header" href="#automatic-client-side-field-level-encryption">Automatic Client-Side Field Level Encryption</a></h2>
<p>Automatic client-side field level encryption is enabled by using the <code>Client::encrypted_builder</code> constructor method. The following examples show how to setup automatic client-side field level encryption using <code>ClientEncryption</code> to create a new encryption data key.</p>
<p><em>Note</em>: Automatic client-side field level encryption requires MongoDB 4.2+ enterprise or a MongoDB 4.2+ Atlas cluster. The community version of the server supports automatic decryption as well as explicit client-side encryption.</p>
<h3 id="providing-local-automatic-encryption-rules"><a class="header" href="#providing-local-automatic-encryption-rules">Providing Local Automatic Encryption Rules</a></h3>
<p>The following example shows how to specify automatic encryption rules via the <code>schema_map</code> option. The automatic encryption rules are expressed using a <a href="https://dochub.mongodb.org/core/client-side-field-level-encryption-automatic-encryption-rules">strict subset of the JSON Schema syntax</a>.</p>
<p>Supplying a <code>schema_map</code> provides more security than relying on JSON Schemas obtained from the server. It protects against a malicious server advertising a false JSON Schema, which could trick the client into sending unencrypted data that should be encrypted.</p>
<p>JSON Schemas supplied in the <code>schema_map</code> only apply to configuring automatic client-side field level encryption. Other validation rules in the JSON schema will not be enforced by the driver and will result in an error.</p>
<!--- Changes to this example should also be made to manual/deps/src/example/local_rules.rs --->
<pre><pre class="playground"><code class="language-rust no_run edition2021"><span class="boring">extern crate mongodb;
</span><span class="boring">extern crate tokio;
</span><span class="boring">extern crate rand;
</span><span class="boring">static URI: &str = "mongodb://example.com";
</span>use mongodb::{
bson::{self, doc, Document},
client_encryption::{ClientEncryption, MasterKey},
error::Result,
mongocrypt::ctx::KmsProvider,
options::ClientOptions,
Client,
Namespace,
};
use rand::Rng;
#[tokio::main]
async fn main() -> Result<()> {
// The MongoDB namespace (db.collection) used to store the
// encrypted documents in this example.
let encrypted_namespace = Namespace::new("test", "coll");
// This must be the same master key that was used to create
// the encryption key.
let mut key_bytes = vec![0u8; 96];
rand::thread_rng().fill(&mut key_bytes[..]);
let local_master_key = bson::Binary {
subtype: bson::spec::BinarySubtype::Generic,
bytes: key_bytes,
};
let kms_providers = vec![(KmsProvider::Local, doc! { "key": local_master_key }, None)];
// The MongoDB namespace (db.collection) used to store
// the encryption data keys.
let key_vault_namespace = Namespace::new("encryption", "__testKeyVault");
// The MongoClient used to access the key vault (key_vault_namespace).
let key_vault_client = Client::with_uri_str(URI).await?;
let key_vault = key_vault_client
.database(&key_vault_namespace.db)
.collection::<Document>(&key_vault_namespace.coll);
key_vault.drop(None).await?;
let client_encryption = ClientEncryption::new(
key_vault_client,
key_vault_namespace.clone(),
kms_providers.clone(),
)?;
// Create a new data key and json schema for the encryptedField.
// https://dochub.mongodb.org/core/client-side-field-level-encryption-automatic-encryption-rules
let data_key_id = client_encryption
.create_data_key(MasterKey::Local)
.key_alt_names(["encryption_example_1".to_string()])
.run()
.await?;
let schema = doc! {
"properties": {
"encryptedField": {
"encrypt": {
"keyId": [data_key_id],
"bsonType": "string",
"algorithm": "AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic",
}
}
},
"bsonType": "object",
};
let client = Client::encrypted_builder(
ClientOptions::parse(URI).await?,
key_vault_namespace,
kms_providers,
)?
.schema_map([(encrypted_namespace.to_string(), schema)])
.build()
.await?;
let coll = client
.database(&encrypted_namespace.db)
.collection::<Document>(&encrypted_namespace.coll);
// Clear old data.
coll.drop(None).await?;
coll.insert_one(doc! { "encryptedField": "123456789" }, None)
.await?;
println!("Decrypted document: {:?}", coll.find_one(None, None).await?);
let unencrypted_coll = Client::with_uri_str(URI)
.await?
.database(&encrypted_namespace.db)
.collection::<Document>(&encrypted_namespace.coll);
println!(
"Encrypted document: {:?}",
unencrypted_coll.find_one(None, None).await?
);
Ok(())
}</code></pre></pre>
<h3 id="server-side-field-level-encryption-enforcement"><a class="header" href="#server-side-field-level-encryption-enforcement">Server-Side Field Level Encryption Enforcement</a></h3>
<p>The MongoDB 4.2+ server supports using schema validation to enforce encryption of specific fields in a collection. This schema validation will prevent an application from inserting unencrypted values for any fields marked with the <code>"encrypt"</code> JSON schema keyword.</p>
<p>The following example shows how to setup automatic client-side field level encryption using <code>ClientEncryption</code> to create a new encryption data key and create a collection with the <a href="https://dochub.mongodb.org/core/client-side-field-level-encryption-automatic-encryption-rules">Automatic Encryption JSON Schema Syntax</a>:</p>
<!--- Changes to this example should also be made to manual/deps/src/example/server_side_enforcement.rs --->
<pre><pre class="playground"><code class="language-rust no_run edition2021"><span class="boring">extern crate mongodb;
</span><span class="boring">extern crate tokio;
</span><span class="boring">extern crate rand;
</span><span class="boring">static URI: &str = "mongodb://example.com";
</span>use mongodb::{
bson::{self, doc, Document},
client_encryption::{ClientEncryption, MasterKey},
error::Result,
mongocrypt::ctx::KmsProvider,
options::{ClientOptions, CreateCollectionOptions, WriteConcern},
Client,
Namespace,
};
use rand::Rng;
#[tokio::main]
async fn main() -> Result<()> {
// The MongoDB namespace (db.collection) used to store the
// encrypted documents in this example.
let encrypted_namespace = Namespace::new("test", "coll");
// This must be the same master key that was used to create
// the encryption key.
let mut key_bytes = vec![0u8; 96];
rand::thread_rng().fill(&mut key_bytes[..]);
let local_master_key = bson::Binary {
subtype: bson::spec::BinarySubtype::Generic,
bytes: key_bytes,
};
let kms_providers = vec![(KmsProvider::Local, doc! { "key": local_master_key }, None)];
// The MongoDB namespace (db.collection) used to store
// the encryption data keys.
let key_vault_namespace = Namespace::new("encryption", "__testKeyVault");
// The MongoClient used to access the key vault (key_vault_namespace).
let key_vault_client = Client::with_uri_str(URI).await?;
let key_vault = key_vault_client
.database(&key_vault_namespace.db)
.collection::<Document>(&key_vault_namespace.coll);
key_vault.drop(None).await?;
let client_encryption = ClientEncryption::new(
key_vault_client,
key_vault_namespace.clone(),
kms_providers.clone(),
)?;
// Create a new data key and json schema for the encryptedField.
let data_key_id = client_encryption
.create_data_key(MasterKey::Local)
.key_alt_names(["encryption_example_2".to_string()])
.run()
.await?;
let schema = doc! {
"properties": {
"encryptedField": {
"encrypt": {
"keyId": [data_key_id],
"bsonType": "string",
"algorithm": "AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic",
}
}
},
"bsonType": "object",
};
let client = Client::encrypted_builder(
ClientOptions::parse(URI).await?,
key_vault_namespace,
kms_providers,
)?
.build()
.await?;
let db = client.database(&encrypted_namespace.db);
let coll = db.collection::<Document>(&encrypted_namespace.coll);
// Clear old data
coll.drop(None).await?;
// Create the collection with the encryption JSON Schema.
db.create_collection(
&encrypted_namespace.coll,
CreateCollectionOptions::builder()
.write_concern(WriteConcern::MAJORITY)
.validator(doc! { "$jsonSchema": schema })
.build(),
).await?;
coll.insert_one(doc! { "encryptedField": "123456789" }, None)
.await?;
println!("Decrypted document: {:?}", coll.find_one(None, None).await?);
let unencrypted_coll = Client::with_uri_str(URI)
.await?
.database(&encrypted_namespace.db)
.collection::<Document>(&encrypted_namespace.coll);
println!(
"Encrypted document: {:?}",
unencrypted_coll.find_one(None, None).await?
);
// This would return a Write error with the message "Document failed validation".
// unencrypted_coll.insert_one(doc! { "encryptedField": "123456789" }, None)
// .await?;
Ok(())
}</code></pre></pre>
<h3 id="automatic-queryable-encryption"><a class="header" href="#automatic-queryable-encryption">Automatic Queryable Encryption</a></h3>
<p>Verison 2.4.0 of the <code>mongodb</code> crate brings support for Queryable Encryption with MongoDB >=6.0.</p>
<p>Queryable Encryption is the second version of Client-Side Field Level Encryption. Data is encrypted client-side. Queryable Encryption supports indexed encrypted fields, which are further processed server-side.</p>
<p>You must have MongoDB 6.0 Enterprise to preview the feature.</p>
<p>Automatic encryption in Queryable Encryption is configured with an <code>encrypted_fields</code> mapping, as demonstrated by the following example:</p>
<!--- Changes to this example should also be made to manual/deps/src/example/automatic_queryable_encryption.rs --->
<pre><pre class="playground"><code class="language-rust no_run edition2021"><span class="boring">extern crate mongodb;
</span><span class="boring">extern crate tokio;
</span><span class="boring">extern crate rand;
</span><span class="boring">extern crate futures;
</span><span class="boring">static URI: &str = "mongodb://example.com";
</span>use futures::TryStreamExt;
use mongodb::{
bson::{self, doc, Document},
client_encryption::{ClientEncryption, MasterKey},
error::Result,
mongocrypt::ctx::KmsProvider,
options::ClientOptions,
Client,
Namespace,
};
use rand::Rng;
#[tokio::main]
async fn main() -> Result<()> {
let mut key_bytes = vec![0u8; 96];
rand::thread_rng().fill(&mut key_bytes[..]);
let local_master_key = bson::Binary {
subtype: bson::spec::BinarySubtype::Generic,
bytes: key_bytes,
};
let kms_providers = vec![(KmsProvider::Local, doc! { "key": local_master_key }, None)];
let key_vault_namespace = Namespace::new("keyvault", "datakeys");
let key_vault_client = Client::with_uri_str(URI).await?;
let key_vault = key_vault_client
.database(&key_vault_namespace.db)
.collection::<Document>(&key_vault_namespace.coll);
key_vault.drop(None).await?;
let client_encryption = ClientEncryption::new(
key_vault_client,
key_vault_namespace.clone(),
kms_providers.clone(),
)?;
let key1_id = client_encryption
.create_data_key(MasterKey::Local)
.key_alt_names(["firstName".to_string()])
.run()
.await?;
let key2_id = client_encryption
.create_data_key(MasterKey::Local)
.key_alt_names(["lastName".to_string()])
.run()
.await?;
let encrypted_fields_map = vec![(
"example.encryptedCollection",
doc! {
"escCollection": "encryptedCollection.esc",
"eccCollection": "encryptedCollection.ecc",
"ecocCollection": "encryptedCollection.ecoc",
"fields": [
{
"path": "firstName",
"bsonType": "string",
"keyId": key1_id,
"queries": [{"queryType": "equality"}],
},
{
"path": "lastName",
"bsonType": "string",
"keyId": key2_id,
}
]
},
)];
let client = Client::encrypted_builder(
ClientOptions::parse(URI).await?,
key_vault_namespace,
kms_providers,
)?
.encrypted_fields_map(encrypted_fields_map)
.build()
.await?;
let db = client.database("example");
let coll = db.collection::<Document>("encryptedCollection");
coll.drop(None).await?;
db.create_collection("encryptedCollection", None).await?;
coll.insert_one(
doc! { "_id": 1, "firstName": "Jane", "lastName": "Doe" },
None,
)
.await?;
let docs: Vec<_> = coll
.find(doc! {"firstName": "Jane"}, None)
.await?
.try_collect()
.await?;
println!("{:?}", docs);
Ok(())
}</code></pre></pre>
<h3 id="explicit-queryable-encryption"><a class="header" href="#explicit-queryable-encryption">Explicit Queryable Encryption</a></h3>
<p>Verison 2.4.0 of the <code>mongodb</code> crate brings support for Queryable Encryption with MongoDB >=6.0.</p>
<p>Queryable Encryption is the second version of Client-Side Field Level Encryption. Data is encrypted client-side. Queryable Encryption supports indexed encrypted fields, which are further processed server-side.</p>
<p>Explicit encryption in Queryable Encryption is performed using the <code>encrypt</code> and <code>decrypt</code> methods. Automatic encryption (to allow the <code>find_one</code> to automatically decrypt) is configured using an <code>encrypted_fields</code> mapping, as demonstrated by the following example:</p>
<!--- Changes to this example should also be made to manual/deps/src/example/explicit_queryable_encryption.rs --->
<pre><pre class="playground"><code class="language-rust no_run edition2021"><span class="boring">extern crate mongodb;
</span><span class="boring">extern crate tokio;
</span><span class="boring">extern crate rand;
</span><span class="boring">static URI: &str = "mongodb://example.com";
</span>use mongodb::{
bson::{self, doc, Document},
client_encryption::{ClientEncryption, MasterKey},
error::Result,
mongocrypt::ctx::{KmsProvider, Algorithm},
options::{ClientOptions, CreateCollectionOptions},
Client,
Namespace,
};
use rand::Rng;
#[tokio::main]
async fn main() -> Result<()> {
// This must be the same master key that was used to create
// the encryption key.
let mut key_bytes = vec![0u8; 96];
rand::thread_rng().fill(&mut key_bytes[..]);
let local_master_key = bson::Binary {
subtype: bson::spec::BinarySubtype::Generic,
bytes: key_bytes,
};
let kms_providers = vec![(KmsProvider::Local, doc! { "key": local_master_key }, None)];
// The MongoDB namespace (db.collection) used to store
// the encryption data keys.
let key_vault_namespace = Namespace::new("keyvault", "datakeys");
// Set up the key vault (key_vault_namespace) for this example.
let client = Client::with_uri_str(URI).await?;
let key_vault = client
.database(&key_vault_namespace.db)
.collection::<Document>(&key_vault_namespace.coll);
key_vault.drop(None).await?;
let client_encryption = ClientEncryption::new(
// The MongoClient to use for reading/writing to the key vault.
// This can be the same MongoClient used by the main application.
client,
key_vault_namespace.clone(),
kms_providers.clone(),
)?;
// Create a new data key for the encryptedField.
let indexed_key_id = client_encryption
.create_data_key(MasterKey::Local)
.run()
.await?;
let unindexed_key_id = client_encryption
.create_data_key(MasterKey::Local)
.run()
.await?;
let encrypted_fields = doc! {
"escCollection": "enxcol_.default.esc",
"eccCollection": "enxcol_.default.ecc",
"ecocCollection": "enxcol_.default.ecoc",
"fields": [
{
"keyId": indexed_key_id.clone(),
"path": "encryptedIndexed",
"bsonType": "string",
"queries": {
"queryType": "equality"
}
},
{
"keyId": unindexed_key_id.clone(),
"path": "encryptedUnindexed",
"bsonType": "string",
}
]
};
// The MongoClient used to read/write application data.
let encrypted_client = Client::encrypted_builder(
ClientOptions::parse(URI).await?,
key_vault_namespace,
kms_providers,
)?
.bypass_query_analysis(true)
.build()
.await?;
let db = encrypted_client.database("test");
db.drop(None).await?;
// Create the collection with encrypted fields.
db.create_collection(
"coll",
CreateCollectionOptions::builder()
.encrypted_fields(encrypted_fields)
.build(),
)
.await?;
let coll = db.collection::<Document>("coll");
// Create and encrypt an indexed and unindexed value.
let val = "encrypted indexed value";
let unindexed_val = "encrypted unindexed value";
let insert_payload_indexed = client_encryption
.encrypt(val, indexed_key_id.clone(), Algorithm::Indexed)
.contention_factor(1)
.run()
.await?;
let insert_payload_unindexed = client_encryption
.encrypt(unindexed_val, unindexed_key_id, Algorithm::Unindexed)
.run()
.await?;
// Insert the payloads.
coll.insert_one(
doc! {
"encryptedIndexed": insert_payload_indexed,
"encryptedUnindexed": insert_payload_unindexed,
},
None,
)
.await?;
// Encrypt our find payload using QueryType.EQUALITY.
// The value of `data_key_id` must be the same as used to encrypt the values
// above.
let find_payload = client_encryption
.encrypt(val, indexed_key_id, Algorithm::Indexed)
.query_type("equality")
.contention_factor(1)
.run()
.await?;
// Find the document we inserted using the encrypted payload.
// The returned document is automatically decrypted.
let doc = coll
.find_one(doc! { "encryptedIndexed": find_payload }, None)
.await?;
println!("Returned document: {:?}", doc);
Ok(())
}</code></pre></pre>
<h2 id="explicit-encryption"><a class="header" href="#explicit-encryption">Explicit Encryption</a></h2>
<p>Explicit encryption is a MongoDB community feature and does not use the mongocryptd process. Explicit encryption is provided by the <code>ClientEncryption</code> struct, for example:</p>
<!--- Changes to this example should also be made to manual/deps/src/example/explicit_encryption.rs --->
<pre><pre class="playground"><code class="language-rust no_run edition2021"><span class="boring">extern crate mongodb;
</span><span class="boring">extern crate tokio;
</span><span class="boring">extern crate rand;
</span><span class="boring">static URI: &str = "mongodb://example.com";
</span>use mongodb::{
bson::{self, doc, Bson, Document},
client_encryption::{ClientEncryption, MasterKey},
error::Result,
mongocrypt::ctx::{Algorithm, KmsProvider},
Client,
Namespace,
};
use rand::Rng;
#[tokio::main]
async fn main() -> Result<()> {
// This must be the same master key that was used to create
// the encryption key.
let mut key_bytes = vec![0u8; 96];
rand::thread_rng().fill(&mut key_bytes[..]);
let local_master_key = bson::Binary {
subtype: bson::spec::BinarySubtype::Generic,
bytes: key_bytes,
};
let kms_providers = vec![(KmsProvider::Local, doc! { "key": local_master_key }, None)];
// The MongoDB namespace (db.collection) used to store
// the encryption data keys.
let key_vault_namespace = Namespace::new("keyvault", "datakeys");
// The MongoClient used to read/write application data.
let client = Client::with_uri_str(URI).await?;
let coll = client.database("test").collection::<Document>("coll");
// Clear old data
coll.drop(None).await?;
// Set up the key vault (key_vault_namespace) for this example.
let key_vault = client
.database(&key_vault_namespace.db)
.collection::<Document>(&key_vault_namespace.coll);
key_vault.drop(None).await?;
let client_encryption = ClientEncryption::new(
// The MongoClient to use for reading/writing to the key vault.
// This can be the same MongoClient used by the main application.
client,
key_vault_namespace.clone(),
kms_providers.clone(),
)?;
// Create a new data key for the encryptedField.
let data_key_id = client_encryption
.create_data_key(MasterKey::Local)
.key_alt_names(["encryption_example_3".to_string()])
.run()
.await?;
// Explicitly encrypt a field:
let encrypted_field = client_encryption
.encrypt(
"123456789",
data_key_id,
Algorithm::AeadAes256CbcHmacSha512Deterministic,
)
.run()
.await?;
coll.insert_one(doc! { "encryptedField": encrypted_field }, None)
.await?;
let mut doc = coll.find_one(None, None).await?.unwrap();
println!("Encrypted document: {:?}", doc);
// Explicitly decrypt the field:
let field = match doc.get("encryptedField") {
Some(Bson::Binary(bin)) => bin,
_ => panic!("invalid field"),
};
let decrypted: Bson = client_encryption
.decrypt(field.as_raw_binary())
.await?
.try_into()?;
doc.insert("encryptedField", decrypted);
println!("Decrypted document: {:?}", doc);
Ok(())
}</code></pre></pre>
<h2 id="explicit-encryption-with-automatic-decryption"><a class="header" href="#explicit-encryption-with-automatic-decryption">Explicit Encryption with Automatic Decryption</a></h2>
<p>Although automatic encryption requires MongoDB 4.2+ enterprise or a MongoDB 4.2+ Atlas cluster, automatic decryption is supported for all users. To configure automatic decryption without automatic encryption set <code>bypass_auto_encryption</code> to <code>true</code> in the <code>EncryptedClientBuilder</code>:</p>
<!--- Changes to this example should also be made to manual/deps/src/example/explicit_encryption_auto_decryption.rs --->
<pre><pre class="playground"><code class="language-rust no_run edition2021"><span class="boring">extern crate mongodb;
</span><span class="boring">extern crate tokio;
</span><span class="boring">extern crate rand;
</span><span class="boring">static URI: &str = "mongodb://example.com";
</span>use mongodb::{
bson::{self, doc, Document},
client_encryption::{ClientEncryption, MasterKey},
error::Result,
mongocrypt::ctx::{Algorithm, KmsProvider},
options::ClientOptions,
Client,
Namespace,
};
use rand::Rng;
#[tokio::main]
async fn main() -> Result<()> {
// This must be the same master key that was used to create
// the encryption key.
let mut key_bytes = vec![0u8; 96];
rand::thread_rng().fill(&mut key_bytes[..]);
let local_master_key = bson::Binary {
subtype: bson::spec::BinarySubtype::Generic,
bytes: key_bytes,
};
let kms_providers = vec![(KmsProvider::Local, doc! { "key": local_master_key }, None)];
// The MongoDB namespace (db.collection) used to store
// the encryption data keys.
let key_vault_namespace = Namespace::new("keyvault", "datakeys");
// `bypass_auto_encryption(true)` disables automatic encryption but keeps
// the automatic _decryption_ behavior. bypass_auto_encryption will
// also disable spawning mongocryptd.
let client = Client::encrypted_builder(
ClientOptions::parse(URI).await?,
key_vault_namespace.clone(),
kms_providers.clone(),
)?
.bypass_auto_encryption(true)
.build()
.await?;
let coll = client.database("test").collection::<Document>("coll");
// Clear old data
coll.drop(None).await?;
// Set up the key vault (key_vault_namespace) for this example.
let key_vault = client
.database(&key_vault_namespace.db)
.collection::<Document>(&key_vault_namespace.coll);
key_vault.drop(None).await?;
let client_encryption = ClientEncryption::new(
// The MongoClient to use for reading/writing to the key vault.
// This can be the same MongoClient used by the main application.
client,
key_vault_namespace.clone(),
kms_providers.clone(),
)?;
// Create a new data key for the encryptedField.
let data_key_id = client_encryption
.create_data_key(MasterKey::Local)
.key_alt_names(["encryption_example_4".to_string()])
.run()
.await?;
// Explicitly encrypt a field:
let encrypted_field = client_encryption
.encrypt(
"123456789",
data_key_id,
Algorithm::AeadAes256CbcHmacSha512Deterministic,
)
.run()
.await?;
coll.insert_one(doc! { "encryptedField": encrypted_field }, None)
.await?;
// Automatically decrypts any encrypted fields.
let doc = coll.find_one(None, None).await?.unwrap();
println!("Decrypted document: {:?}", doc);
let unencrypted_coll = Client::with_uri_str(URI)
.await?
.database("test")
.collection::<Document>("coll");
println!(
"Encrypted document: {:?}",
unencrypted_coll.find_one(None, None).await?
);
Ok(())
}</code></pre></pre>
</main>
<nav class="nav-wrapper" aria-label="Page navigation">
<!-- Mobile navigation buttons -->
<div style="clear: both"></div>
</nav>
</div>
</div>
<nav class="nav-wide-wrapper" aria-label="Page navigation">
</nav>
</div>
<!-- Livereload script (if served using the cli tool) -->
<script>
const wsProtocol = location.protocol === 'https:' ? 'wss:' : 'ws:';
const wsAddress = wsProtocol + "//" + location.host + "/" + "__livereload";
const socket = new WebSocket(wsAddress);
socket.onmessage = function (event) {
if (event.data === "reload") {
socket.close();
location.reload();
}
};
window.onbeforeunload = function() {
socket.close();
}
</script>
<script>
window.playground_copyable = true;
</script>
<script src="elasticlunr.min.js"></script>
<script src="mark.min.js"></script>
<script src="searcher.js"></script>
<script src="clipboard.min.js"></script>
<script src="highlight.js"></script>
<script src="book.js"></script>
<!-- Custom JS scripts -->
<script>
window.addEventListener('load', function() {
window.setTimeout(window.print, 100);
});
</script>
</div>
</body>
</html>