mongodb 2.8.2

The official MongoDB driver for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
<!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() -&gt; std::result::Result&lt;(), Box&lt;dyn std::error::Error&gt;&gt; {
</span><span class="boring">
</span><span class="boring">let client = Client::with_uri_str(&quot;mongodb://example.com&quot;).await?;
</span>let collection = client.database(&quot;foo&quot;).collection(&quot;bar&quot;);
let handle = tokio::task::spawn(async move {
    collection.insert_one(doc! { &quot;x&quot;: 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 = &quot;2.1.0&quot;
</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>&quot;tokio-runtime&quot;</code> or <code>&quot;async-std-runtime&quot;</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 = &quot;2.7.0&quot;
default-features = false
features = [&quot;async-std-runtime&quot;]
</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>&quot;sync&quot;</code> or <code>&quot;tokio-sync&quot;</code> feature to your <code>Cargo.toml</code>:</p>
<pre><code class="language-toml">[dependencies.mongodb]
version = &quot;2.7.0&quot;
features = [&quot;tokio-sync&quot;]
</code></pre>
<p>Using the <code>&quot;sync&quot;</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() -&gt; mongodb::error::Result&lt;()&gt; {
</span>let mut options = ClientOptions::parse(&quot;mongodb://mongodb0.example.com:27017&quot;).await?;
options.app_name = Some(&quot;My App&quot;.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() -&gt; mongodb::error::Result&lt;()&gt; {
</span><span class="boring">let options = ClientOptions::parse(&quot;mongodb://mongodb0.example.com:27017&quot;).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() -&gt; mongodb::error::Result&lt;()&gt; {
</span>let client = Client::with_uri_str(&quot;mongodb://mongodb0.example.com:27017&quot;).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() -&gt; Result&lt;()&gt; {
</span>let client = Client::with_uri_str(&quot;mongodb://example.com&quot;).await?;

for i in 0..5 {
    let client_ref = client.clone();

    task::spawn(async move {
        let collection = client_ref.database(&quot;items&quot;).collection::&lt;Document&gt;(&amp;format!(&quot;coll{}&quot;, 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() -&gt; Result&lt;()&gt; {
</span><span class="boring">let client = Client::with_uri_str(&quot;mongodb://example.com&quot;).await?;
</span>let db = client.database(&quot;items&quot;);

for i in 0..5 {
    let db_ref = db.clone();

    task::spawn(async move {
        let collection = db_ref.collection::&lt;Document&gt;(&amp;format!(&quot;coll{}&quot;, 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() -&gt; Result&lt;()&gt; {
</span><span class="boring">use mongodb::Client;
</span><span class="boring">
</span><span class="boring">let client = Client::with_uri_str(&quot;mongodb://example.com&quot;).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(&quot;items&quot;).collection::&lt;Item&gt;(&quot;in_stock&quot;);

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 = &quot;0.3&quot;
</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() -&gt; mongodb::error::Result&lt;()&gt; {
</span><span class="boring">let typed_collection = mongodb::Client::with_uri_str(&quot;&quot;).await?.database(&quot;&quot;).collection::&lt;Book&gt;(&quot;&quot;);
</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! { &quot;author&quot;: &quot;George Orwell&quot; };
let find_options = FindOptions::builder().sort(doc! { &quot;title&quot;: 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!(&quot;title: {}&quot;, 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() -&gt; Result&lt;(), Box&lt;dyn Error&gt;&gt; {
    let client = Client::with_uri_str(&quot;mongodb://example.com&quot;).await?;
    // Do something with the client
    Ok(())
}

// This will be much faster.
async fn handle_request_good(client: &amp;Client) -&gt; Result&lt;(), Box&lt;dyn Error&gt;&gt; {
    // 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&lt;Client&gt; = Lazy::new(|| {
    let rt = Runtime::new().unwrap();
    rt.block_on(async {
        Client::with_uri_str(&quot;mongodb://example.com&quot;).await.unwrap()
    })
});

// This will inconsistently fail.
#[tokio::test]
async fn test_list_dbs() -&gt; Result&lt;(), Box&lt;dyn Error&gt;&gt; {
    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&lt;(Client, Runtime)&gt; = Lazy::new(|| {
    let rt = Runtime::new().unwrap();
    let client = rt.block_on(async {
        Client::with_uri_str(&quot;mongodb://example.com&quot;).await.unwrap()
    });
    (client, rt)
});

#[test]
fn test_list_dbs() -&gt; Result&lt;(), Box&lt;dyn Error&gt;&gt; {
    let (client, rt) = &amp;*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() -&gt; Result&lt;(), Box&lt;dyn Error&gt;&gt; {
    let client = Client::with_uri_str(&quot;mongodb://example.com&quot;).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() -&gt; Result&lt;()&gt; {
</span>let client = Client::with_uri_str(&quot;mongodb://example.com&quot;).await?;

for i in 0..5 {
    let client_ref = client.clone();

    task::spawn(async move {
        let collection = client_ref.database(&quot;items&quot;).collection::&lt;Document&gt;(&amp;format!(&quot;coll{}&quot;, 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 = &quot;LATEST_VERSION_HERE&quot;
tracing-subscriber = &quot;LATEST_VERSION_HERE&quot;
mongodb = { version = &quot;LATEST_VERSION_HERE&quot;, features = [&quot;tracing-unstable&quot;] }
</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() -&gt; Result&lt;()&gt; {
    // 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(&quot;MONGODB_URI&quot;).expect(&quot;The MONGODB_URI environment variable was not set.&quot;);
    let client = Client::with_uri_str(mongodb_uri).await?;

    // Insert a document.
    let coll = client.database(&quot;test&quot;).collection(&quot;test_coll&quot;);
    coll.insert_one(doc! { &quot;x&quot; : 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=&quot;63dd5e706af9908fc834fd94&quot; command=&quot;{\&quot;insert\&quot;:\&quot;test_coll\&quot;,\&quot;ordered\&quot;:true,\&quot;$db\&quot;:\&quot;test\&quot;,\&quot;lsid\&quot;:{\&quot;id\&quot;:{\&quot;$binary\&quot;:{\&quot;base64\&quot;:\&quot;y/v7PiLaRwOhT0RBFRDtNw==\&quot;,\&quot;subType\&quot;:\&quot;04\&quot;}}},\&quot;documents\&quot;:[{\&quot;_id\&quot;:{\&quot;$oid\&quot;:\&quot;63dd5e706af9908fc834fd95\&quot;},\&quot;x\&quot;:1}]}&quot; databaseName=&quot;test&quot; commandName=&quot;insert&quot; requestId=4 driverConnectionId=1 serverConnectionId=16 serverHost=&quot;localhost&quot; serverPort=27017
2023-02-03T19:20:16.092700Z DEBUG mongodb::command: Command succeeded topologyId=&quot;63dd5e706af9908fc834fd94&quot; reply=&quot;{\&quot;n\&quot;:1,\&quot;ok\&quot;:1.0}&quot; commandName=&quot;insert&quot; requestId=4 driverConnectionId=1 serverConnectionId=16 serverHost=&quot;localhost&quot; 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 = &quot;LATEST_VERSION_HERE&quot;, features = [&quot;log&quot;] }
mongodb = { version = &quot;LATEST_VERSION_HERE&quot;, features = [&quot;tracing-unstable&quot;] }
env_logger = &quot;LATEST_VERSION_HERE&quot;
</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() -&gt; Result&lt;()&gt; {
    // Register a global logger.
    env_logger::init();

    // Create a MongoDB client.
    let mongodb_uri =
        env::var(&quot;MONGODB_URI&quot;).expect(&quot;The MONGODB_URI environment variable was not set.&quot;);
    let client = Client::with_uri_str(mongodb_uri).await?;

    // Insert a document.
    let coll = client.database(&quot;test&quot;).collection(&quot;test_coll&quot;);
    coll.insert_one(doc! { &quot;x&quot; : 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=&quot;63dd5e706af9908fc834fd94&quot; command=&quot;{\&quot;insert\&quot;:\&quot;test_coll\&quot;,\&quot;ordered\&quot;:true,\&quot;$db\&quot;:\&quot;test\&quot;,\&quot;lsid\&quot;:{\&quot;id\&quot;:{\&quot;$binary\&quot;:{\&quot;base64\&quot;:\&quot;y/v7PiLaRwOhT0RBFRDtNw==\&quot;,\&quot;subType\&quot;:\&quot;04\&quot;}}},\&quot;documents\&quot;:[{\&quot;_id\&quot;:{\&quot;$oid\&quot;:\&quot;63dd5e706af9908fc834fd95\&quot;},\&quot;x\&quot;:1}]}&quot; databaseName=&quot;test&quot; commandName=&quot;insert&quot; requestId=4 driverConnectionId=1 serverConnectionId=16 serverHost=&quot;localhost&quot; serverPort=27017
2023-02-03T19:20:16.092700Z DEBUG mongodb::command: Command succeeded topologyId=&quot;63dd5e706af9908fc834fd94&quot; reply=&quot;{\&quot;n\&quot;:1,\&quot;ok\&quot;:1.0}&quot; commandName=&quot;insert&quot; requestId=4 driverConnectionId=1 serverConnectionId=16 serverHost=&quot;localhost&quot; 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>&quot;in-use-encryption-unstable&quot;</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>&quot;cryptSharedLibPath&quot;</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() -&gt; Result&lt;()&gt; {
</span><span class="boring">let options = todo!();
</span><span class="boring">let kv_namespace = todo!();
</span><span class="boring">let kms_providers: Vec&lt;_&gt; = todo!();
</span>let client = Client::encrypted_builder(options, kv_namespace, kms_providers)?
    .extra_options(doc! {
        &quot;cryptSharedLibPath&quot;: &quot;/path/to/crypt/shared&quot;,
    })
    .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>&quot;cryptSharedRequired&quot;: 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() -&gt; Result&lt;()&gt; {
</span><span class="boring">let options = todo!();
</span><span class="boring">let kv_namespace = todo!();
</span><span class="boring">let kms_providers: Vec&lt;_&gt; = todo!();
</span>let client = Client::encrypted_builder(options, kv_namespace, kms_providers)?
    .extra_options(doc! {
        &quot;mongocryptdSpawnPath&quot;: &quot;/path/to/mongocryptd&quot;,
        &quot;mongocryptdSpawnArgs&quot;: [&quot;--logpath=/path/to/mongocryptd.log&quot;, &quot;--logappend&quot;],
    })
    .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() -&gt; Result&lt;()&gt; {
</span><span class="boring">let options = todo!();
</span><span class="boring">let kv_namespace = todo!();
</span><span class="boring">let kms_providers: Vec&lt;_&gt; = todo!();
</span>let client = Client::encrypted_builder(options, kv_namespace, kms_providers)?
    .extra_options(doc! {
        &quot;mongocryptdBypassSpawn&quot;: true,
        &quot;mongocryptdURI&quot;: &quot;mongodb://localhost:27020&quot;,
    })
    .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: &amp;str = &quot;mongodb://example.com&quot;;
</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() -&gt; Result&lt;()&gt; {
    // The MongoDB namespace (db.collection) used to store the
    // encrypted documents in this example.
    let encrypted_namespace = Namespace::new(&quot;test&quot;, &quot;coll&quot;);

    // 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(&amp;mut key_bytes[..]);
    let local_master_key = bson::Binary {
        subtype: bson::spec::BinarySubtype::Generic,
        bytes: key_bytes,
    };
    let kms_providers = vec![(KmsProvider::Local, doc! { &quot;key&quot;: local_master_key }, None)];

    // The MongoDB namespace (db.collection) used to store
    // the encryption data keys.
    let key_vault_namespace = Namespace::new(&quot;encryption&quot;, &quot;__testKeyVault&quot;);

    // 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(&amp;key_vault_namespace.db)
        .collection::&lt;Document&gt;(&amp;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([&quot;encryption_example_1&quot;.to_string()])
        .run()
        .await?;
    let schema = doc! {
        &quot;properties&quot;: {
            &quot;encryptedField&quot;: {
                &quot;encrypt&quot;: {
                    &quot;keyId&quot;: [data_key_id],
                    &quot;bsonType&quot;: &quot;string&quot;,
                    &quot;algorithm&quot;: &quot;AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic&quot;,
                }
            }
        },
        &quot;bsonType&quot;: &quot;object&quot;,
    };

    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(&amp;encrypted_namespace.db)
        .collection::&lt;Document&gt;(&amp;encrypted_namespace.coll);
    // Clear old data.
    coll.drop(None).await?;

    coll.insert_one(doc! { &quot;encryptedField&quot;: &quot;123456789&quot; }, None)
        .await?;
    println!(&quot;Decrypted document: {:?}&quot;, coll.find_one(None, None).await?);
    let unencrypted_coll = Client::with_uri_str(URI)
        .await?
        .database(&amp;encrypted_namespace.db)
        .collection::&lt;Document&gt;(&amp;encrypted_namespace.coll);
    println!(
        &quot;Encrypted document: {:?}&quot;,
        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>&quot;encrypt&quot;</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: &amp;str = &quot;mongodb://example.com&quot;;
</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() -&gt; Result&lt;()&gt; {
    // The MongoDB namespace (db.collection) used to store the
    // encrypted documents in this example.
    let encrypted_namespace = Namespace::new(&quot;test&quot;, &quot;coll&quot;);

    // 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(&amp;mut key_bytes[..]);
    let local_master_key = bson::Binary {
        subtype: bson::spec::BinarySubtype::Generic,
        bytes: key_bytes,
    };
    let kms_providers = vec![(KmsProvider::Local, doc! { &quot;key&quot;: local_master_key }, None)];

    // The MongoDB namespace (db.collection) used to store
    // the encryption data keys.
    let key_vault_namespace = Namespace::new(&quot;encryption&quot;, &quot;__testKeyVault&quot;);

    // 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(&amp;key_vault_namespace.db)
        .collection::&lt;Document&gt;(&amp;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([&quot;encryption_example_2&quot;.to_string()])
        .run()
        .await?;
    let schema = doc! {
        &quot;properties&quot;: {
            &quot;encryptedField&quot;: {
                &quot;encrypt&quot;: {
                    &quot;keyId&quot;: [data_key_id],
                    &quot;bsonType&quot;: &quot;string&quot;,
                    &quot;algorithm&quot;: &quot;AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic&quot;,
                }
            }
        },
        &quot;bsonType&quot;: &quot;object&quot;,
    };
    
    let client = Client::encrypted_builder(
        ClientOptions::parse(URI).await?,
        key_vault_namespace,
        kms_providers,
    )?
    .build()
    .await?;
    let db = client.database(&amp;encrypted_namespace.db);
    let coll = db.collection::&lt;Document&gt;(&amp;encrypted_namespace.coll);
    // Clear old data
    coll.drop(None).await?;
    // Create the collection with the encryption JSON Schema.
    db.create_collection(
        &amp;encrypted_namespace.coll,
        CreateCollectionOptions::builder()
            .write_concern(WriteConcern::MAJORITY)
            .validator(doc! { &quot;$jsonSchema&quot;: schema })
            .build(),
    ).await?;

    coll.insert_one(doc! { &quot;encryptedField&quot;: &quot;123456789&quot; }, None)
        .await?;
    println!(&quot;Decrypted document: {:?}&quot;, coll.find_one(None, None).await?);
    let unencrypted_coll = Client::with_uri_str(URI)
        .await?
        .database(&amp;encrypted_namespace.db)
        .collection::&lt;Document&gt;(&amp;encrypted_namespace.coll);
    println!(
        &quot;Encrypted document: {:?}&quot;,
        unencrypted_coll.find_one(None, None).await?
    );
    // This would return a Write error with the message &quot;Document failed validation&quot;.
    // unencrypted_coll.insert_one(doc! { &quot;encryptedField&quot;: &quot;123456789&quot; }, 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 &gt;=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: &amp;str = &quot;mongodb://example.com&quot;;
</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() -&gt; Result&lt;()&gt; {
    let mut key_bytes = vec![0u8; 96];
    rand::thread_rng().fill(&amp;mut key_bytes[..]);
    let local_master_key = bson::Binary {
        subtype: bson::spec::BinarySubtype::Generic,
        bytes: key_bytes,
    };
    let kms_providers = vec![(KmsProvider::Local, doc! { &quot;key&quot;: local_master_key }, None)];
    let key_vault_namespace = Namespace::new(&quot;keyvault&quot;, &quot;datakeys&quot;);
    let key_vault_client = Client::with_uri_str(URI).await?;
    let key_vault = key_vault_client
        .database(&amp;key_vault_namespace.db)
        .collection::&lt;Document&gt;(&amp;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([&quot;firstName&quot;.to_string()])
        .run()
        .await?;
    let key2_id = client_encryption
        .create_data_key(MasterKey::Local)
        .key_alt_names([&quot;lastName&quot;.to_string()])
        .run()
        .await?;

    let encrypted_fields_map = vec![(
        &quot;example.encryptedCollection&quot;,
        doc! {
            &quot;escCollection&quot;: &quot;encryptedCollection.esc&quot;,
            &quot;eccCollection&quot;: &quot;encryptedCollection.ecc&quot;,
            &quot;ecocCollection&quot;: &quot;encryptedCollection.ecoc&quot;,
            &quot;fields&quot;: [
              {
                &quot;path&quot;: &quot;firstName&quot;,
                &quot;bsonType&quot;: &quot;string&quot;,
                &quot;keyId&quot;: key1_id,
                &quot;queries&quot;: [{&quot;queryType&quot;: &quot;equality&quot;}],
              },
                {
                  &quot;path&quot;: &quot;lastName&quot;,
                  &quot;bsonType&quot;: &quot;string&quot;,
                  &quot;keyId&quot;: 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(&quot;example&quot;);
    let coll = db.collection::&lt;Document&gt;(&quot;encryptedCollection&quot;);
    coll.drop(None).await?;
    db.create_collection(&quot;encryptedCollection&quot;, None).await?;
    coll.insert_one(
        doc! { &quot;_id&quot;: 1, &quot;firstName&quot;: &quot;Jane&quot;, &quot;lastName&quot;: &quot;Doe&quot; },
        None,
    )
    .await?;
    let docs: Vec&lt;_&gt; = coll
        .find(doc! {&quot;firstName&quot;: &quot;Jane&quot;}, None)
        .await?
        .try_collect()
        .await?;
    println!(&quot;{:?}&quot;, 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 &gt;=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: &amp;str = &quot;mongodb://example.com&quot;;
</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() -&gt; Result&lt;()&gt; {
    // 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(&amp;mut key_bytes[..]);
    let local_master_key = bson::Binary {
        subtype: bson::spec::BinarySubtype::Generic,
        bytes: key_bytes,
    };
    let kms_providers = vec![(KmsProvider::Local, doc! { &quot;key&quot;: local_master_key }, None)];

    // The MongoDB namespace (db.collection) used to store
    // the encryption data keys.
    let key_vault_namespace = Namespace::new(&quot;keyvault&quot;, &quot;datakeys&quot;);

    // Set up the key vault (key_vault_namespace) for this example.
    let client = Client::with_uri_str(URI).await?;
    let key_vault = client
        .database(&amp;key_vault_namespace.db)
        .collection::&lt;Document&gt;(&amp;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! {
      &quot;escCollection&quot;: &quot;enxcol_.default.esc&quot;,
      &quot;eccCollection&quot;: &quot;enxcol_.default.ecc&quot;,
      &quot;ecocCollection&quot;: &quot;enxcol_.default.ecoc&quot;,
      &quot;fields&quot;: [
        {
          &quot;keyId&quot;: indexed_key_id.clone(),
          &quot;path&quot;: &quot;encryptedIndexed&quot;,
          &quot;bsonType&quot;: &quot;string&quot;,
          &quot;queries&quot;: {
            &quot;queryType&quot;: &quot;equality&quot;
          }
        },
        {
          &quot;keyId&quot;: unindexed_key_id.clone(),
          &quot;path&quot;: &quot;encryptedUnindexed&quot;,
          &quot;bsonType&quot;: &quot;string&quot;,
        }
      ]
    };

    // 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(&quot;test&quot;);
    db.drop(None).await?;

    // Create the collection with encrypted fields.
    db.create_collection(
        &quot;coll&quot;,
        CreateCollectionOptions::builder()
            .encrypted_fields(encrypted_fields)
            .build(),
    )
    .await?;
    let coll = db.collection::&lt;Document&gt;(&quot;coll&quot;);

    // Create and encrypt an indexed and unindexed value.
    let val = &quot;encrypted indexed value&quot;;
    let unindexed_val = &quot;encrypted unindexed value&quot;;
    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! {
            &quot;encryptedIndexed&quot;: insert_payload_indexed,
            &quot;encryptedUnindexed&quot;: 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(&quot;equality&quot;)
        .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! { &quot;encryptedIndexed&quot;: find_payload }, None)
        .await?;
    println!(&quot;Returned document: {:?}&quot;, 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: &amp;str = &quot;mongodb://example.com&quot;;
</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() -&gt; Result&lt;()&gt; {
    // 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(&amp;mut key_bytes[..]);
    let local_master_key = bson::Binary {
        subtype: bson::spec::BinarySubtype::Generic,
        bytes: key_bytes,
    };
    let kms_providers = vec![(KmsProvider::Local, doc! { &quot;key&quot;: local_master_key }, None)];

    // The MongoDB namespace (db.collection) used to store
    // the encryption data keys.
    let key_vault_namespace = Namespace::new(&quot;keyvault&quot;, &quot;datakeys&quot;);

    // The MongoClient used to read/write application data.
    let client = Client::with_uri_str(URI).await?;
    let coll = client.database(&quot;test&quot;).collection::&lt;Document&gt;(&quot;coll&quot;);
    // Clear old data
    coll.drop(None).await?;

    // Set up the key vault (key_vault_namespace) for this example.
    let key_vault = client
        .database(&amp;key_vault_namespace.db)
        .collection::&lt;Document&gt;(&amp;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([&quot;encryption_example_3&quot;.to_string()])
        .run()
        .await?;

    // Explicitly encrypt a field:
    let encrypted_field = client_encryption
        .encrypt(
            &quot;123456789&quot;,
            data_key_id,
            Algorithm::AeadAes256CbcHmacSha512Deterministic,
        )
        .run()
        .await?;
    coll.insert_one(doc! { &quot;encryptedField&quot;: encrypted_field }, None)
        .await?;
    let mut doc = coll.find_one(None, None).await?.unwrap();
    println!(&quot;Encrypted document: {:?}&quot;, doc);

    // Explicitly decrypt the field:
    let field = match doc.get(&quot;encryptedField&quot;) {
        Some(Bson::Binary(bin)) =&gt; bin,
        _ =&gt; panic!(&quot;invalid field&quot;),
    };
    let decrypted: Bson = client_encryption
        .decrypt(field.as_raw_binary())
        .await?
        .try_into()?;
    doc.insert(&quot;encryptedField&quot;, decrypted);
    println!(&quot;Decrypted document: {:?}&quot;, 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: &amp;str = &quot;mongodb://example.com&quot;;
</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() -&gt; Result&lt;()&gt; {
    // 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(&amp;mut key_bytes[..]);
    let local_master_key = bson::Binary {
        subtype: bson::spec::BinarySubtype::Generic,
        bytes: key_bytes,
    };
    let kms_providers = vec![(KmsProvider::Local, doc! { &quot;key&quot;: local_master_key }, None)];

    // The MongoDB namespace (db.collection) used to store
    // the encryption data keys.
    let key_vault_namespace = Namespace::new(&quot;keyvault&quot;, &quot;datakeys&quot;);

    // `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(&quot;test&quot;).collection::&lt;Document&gt;(&quot;coll&quot;);
    // Clear old data
    coll.drop(None).await?;

    // Set up the key vault (key_vault_namespace) for this example.
    let key_vault = client
        .database(&amp;key_vault_namespace.db)
        .collection::&lt;Document&gt;(&amp;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([&quot;encryption_example_4&quot;.to_string()])
        .run()
        .await?;

    // Explicitly encrypt a field:
    let encrypted_field = client_encryption
        .encrypt(
            &quot;123456789&quot;,
            data_key_id,
            Algorithm::AeadAes256CbcHmacSha512Deterministic,
        )
        .run()
        .await?;
    coll.insert_one(doc! { &quot;encryptedField&quot;: encrypted_field }, None)
        .await?;
    // Automatically decrypts any encrypted fields.
    let doc = coll.find_one(None, None).await?.unwrap();
    println!(&quot;Decrypted document: {:?}&quot;, doc);
    let unencrypted_coll = Client::with_uri_str(URI)
        .await?
        .database(&quot;test&quot;)
        .collection::&lt;Document&gt;(&quot;coll&quot;);
    println!(
        &quot;Encrypted document: {:?}&quot;,
        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>