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
use std::time::Duration;

use serde::{de::Error, Deserialize, Deserializer, Serialize, Serializer};
use serde_with::skip_serializing_none;
use typed_builder::TypedBuilder;

use crate::{
    bson::{doc, serde_helpers, Bson, Document, RawBson, RawDocumentBuf},
    concern::{ReadConcern, WriteConcern},
    error::Result,
    options::Collation,
    selection_criteria::SelectionCriteria,
    serde_util::{self, write_concern_is_empty},
};

// Generated code for `Deserialize` or `TypedBuilder` causes a deprecation warning; annotating the
// field or struct doesn't fix it because that annotation isn't propagated by the code generator.
// This works around that by defining it in a non-pub module and immediately re-exporting that
// module's contents.
#[allow(deprecated)]
mod suppress_warning {
    use super::*;

    /// These are the valid options for creating a [`Collection`](crate::Collection) with
    /// [`Database::collection_with_options`](crate::Database::collection_with_options).
    #[derive(Clone, Debug, Default, Deserialize, TypedBuilder)]
    #[builder(field_defaults(default, setter(into)))]
    #[serde(rename_all = "camelCase")]
    #[non_exhaustive]
    pub struct CollectionOptions {
        /// The default read preference for operations.
        pub selection_criteria: Option<SelectionCriteria>,

        /// The default read concern for operations.
        pub read_concern: Option<ReadConcern>,

        /// The default write concern for operations.
        pub write_concern: Option<WriteConcern>,

        /// Sets the [`bson::SerializerOptions::human_readable`] option for the [`Bson`]
        /// serializer. The default value is `false`.
        /// Note: Specifying `true` for this value will decrease the performance of insert
        /// operations.
        #[deprecated = "This is a workaround for a potential bug related to RUST-1687, and should \
                        not be used in new code."]
        pub human_readable_serialization: Option<bool>,
    }
}
pub use suppress_warning::*;

/// Specifies whether a
/// [`Collection::find_one_and_replace`](../struct.Collection.html#method.find_one_and_replace) and
/// [`Collection::find_one_and_update`](../struct.Collection.html#method.find_one_and_update)
/// operation should return the document before or after modification.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum ReturnDocument {
    /// Return the document after modification.
    After,
    /// Return the document before modification.
    Before,
}

impl<'de> Deserialize<'de> for ReturnDocument {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> std::result::Result<Self, D::Error> {
        let s = String::deserialize(deserializer)?;
        match s.to_lowercase().as_str() {
            "after" => Ok(ReturnDocument::After),
            "before" => Ok(ReturnDocument::Before),
            other => Err(D::Error::custom(format!(
                "Unknown return document value: {}",
                other
            ))),
        }
    }
}

/// Specifies the index to use for an operation.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
#[serde(untagged)]
#[non_exhaustive]
pub enum Hint {
    /// Specifies the keys of the index to use.
    Keys(Document),
    /// Specifies the name of the index to use.
    Name(String),
}

impl Hint {
    pub(crate) fn to_raw_bson(&self) -> Result<RawBson> {
        Ok(match self {
            Hint::Keys(ref d) => RawBson::Document(RawDocumentBuf::from_document(d)?),
            Hint::Name(ref s) => RawBson::String(s.clone()),
        })
    }
}

/// Specifies the type of cursor to return from a find operation.
#[derive(Debug, Clone, Copy, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub enum CursorType {
    /// Default; close the cursor after the last document is received from the server.
    NonTailable,

    /// Do not close the cursor after the last document is received from the server. If more
    /// results become available later, the cursor will return them.
    Tailable,

    /// Similar to `Tailable`, except that the cursor should block on receiving more results if
    /// none are available.
    TailableAwait,
}

/// Specifies the options to a
/// [`Collection::insert_one`](../struct.Collection.html#method.insert_one) operation.
#[skip_serializing_none]
#[derive(Clone, Debug, Default, Deserialize, TypedBuilder)]
#[serde(rename_all = "camelCase")]
#[builder(field_defaults(default, setter(into)))]
#[non_exhaustive]
pub struct InsertOneOptions {
    /// Opt out of document-level validation.
    pub bypass_document_validation: Option<bool>,

    /// The write concern for the operation.
    pub write_concern: Option<WriteConcern>,

    /// Tags the query with an arbitrary [`Bson`] value to help trace the operation through the
    /// database profiler, currentOp and logs.
    ///
    /// This option is only available on server versions 4.4+.
    pub comment: Option<Bson>,
}

/// Specifies the options to a
/// [`Collection::insert_many`](../struct.Collection.html#method.insert_many) operation.
#[skip_serializing_none]
#[derive(Clone, Debug, Default, TypedBuilder, Serialize, Deserialize)]
#[builder(field_defaults(default, setter(into)))]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct InsertManyOptions {
    /// Opt out of document-level validation.
    pub bypass_document_validation: Option<bool>,

    /// If true, when an insert fails, return without performing the remaining writes. If false,
    /// when a write fails, continue with the remaining writes, if any.
    ///
    /// Defaults to true.
    pub ordered: Option<bool>,

    /// The write concern for the operation.
    #[serde(skip_deserializing, skip_serializing_if = "write_concern_is_empty")]
    pub write_concern: Option<WriteConcern>,

    /// Tags the query with an arbitrary [`Bson`] value to help trace the operation through the
    /// database profiler, currentOp and logs.
    ///
    /// This option is only available on server versions 4.4+.
    pub comment: Option<Bson>,
}

impl InsertManyOptions {
    pub(crate) fn from_insert_one_options(options: InsertOneOptions) -> Self {
        Self {
            bypass_document_validation: options.bypass_document_validation,
            ordered: None,
            write_concern: options.write_concern,
            comment: options.comment,
        }
    }
}

/// Enum modeling the modifications to apply during an update.
/// For details, see the official MongoDB
/// [documentation](https://www.mongodb.com/docs/manual/reference/command/update/#update-command-behaviors)
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(untagged)]
#[non_exhaustive]
pub enum UpdateModifications {
    /// A document that contains only update operator expressions.
    Document(Document),

    /// An aggregation pipeline.
    /// Only available in MongoDB 4.2+.
    Pipeline(Vec<Document>),
}

impl From<Document> for UpdateModifications {
    fn from(item: Document) -> Self {
        UpdateModifications::Document(item)
    }
}

impl From<Vec<Document>> for UpdateModifications {
    fn from(item: Vec<Document>) -> Self {
        UpdateModifications::Pipeline(item)
    }
}

/// Specifies the options to a
/// [`Collection::update_one`](../struct.Collection.html#method.update_one) or
/// [`Collection::update_many`](../struct.Collection.html#method.update_many) operation.
#[skip_serializing_none]
#[derive(Clone, Debug, Default, Deserialize, TypedBuilder)]
#[serde(rename_all = "camelCase")]
#[builder(field_defaults(default, setter(into)))]
#[non_exhaustive]
pub struct UpdateOptions {
    /// A set of filters specifying to which array elements an update should apply.
    ///
    /// See the documentation [here](https://www.mongodb.com/docs/manual/reference/command/update/) for
    /// more information on array filters.
    pub array_filters: Option<Vec<Document>>,

    /// Opt out of document-level validation.
    pub bypass_document_validation: Option<bool>,

    /// If true, insert a document if no matching document is found.
    pub upsert: Option<bool>,

    /// The collation to use for the operation.
    ///
    /// See the [documentation](https://www.mongodb.com/docs/manual/reference/collation/) for more
    /// information on how to use this option.
    pub collation: Option<Collation>,

    /// A document or string that specifies the index to use to support the query predicate.
    ///
    /// Only available in MongoDB 4.2+. See the official MongoDB
    /// [documentation](https://www.mongodb.com/docs/manual/reference/command/update/#ex-update-command-hint) for examples.
    pub hint: Option<Hint>,

    /// The write concern for the operation.
    pub write_concern: Option<WriteConcern>,

    /// Map of parameter names and values. Values must be constant or closed
    /// expressions that do not reference document fields. Parameters can then be
    /// accessed as variables in an aggregate expression context (e.g. "$$var").
    ///
    /// Only available in MongoDB 5.0+.
    #[serde(rename = "let")]
    pub let_vars: Option<Document>,

    /// Tags the query with an arbitrary [`Bson`] value to help trace the operation through the
    /// database profiler, currentOp and logs.
    ///
    /// This option is only available on server versions 4.4+.
    pub comment: Option<Bson>,
}

impl UpdateOptions {
    pub(crate) fn from_replace_options(options: ReplaceOptions) -> Self {
        Self {
            bypass_document_validation: options.bypass_document_validation,
            upsert: options.upsert,
            hint: options.hint,
            write_concern: options.write_concern,
            collation: options.collation,
            let_vars: options.let_vars,
            comment: options.comment,
            ..Default::default()
        }
    }
}

/// Specifies the options to a
/// [`Collection::replace_one`](../struct.Collection.html#method.replace_one) operation.
#[skip_serializing_none]
#[derive(Clone, Debug, Default, Deserialize, TypedBuilder)]
#[serde(rename_all = "camelCase")]
#[builder(field_defaults(default, setter(into)))]
#[non_exhaustive]
pub struct ReplaceOptions {
    /// Opt out of document-level validation.
    pub bypass_document_validation: Option<bool>,

    /// If true, insert a document if no matching document is found.
    pub upsert: Option<bool>,

    /// The collation to use for the operation.
    ///
    /// See the [documentation](https://www.mongodb.com/docs/manual/reference/collation/) for more
    /// information on how to use this option.
    pub collation: Option<Collation>,

    /// A document or string that specifies the index to use to support the query predicate.
    ///
    /// Only available in MongoDB 4.2+. See the official MongoDB
    /// [documentation](https://www.mongodb.com/docs/manual/reference/command/update/#ex-update-command-hint) for examples.
    pub hint: Option<Hint>,

    /// The write concern for the operation.
    pub write_concern: Option<WriteConcern>,

    /// Map of parameter names and values. Values must be constant or closed
    /// expressions that do not reference document fields. Parameters can then be
    /// accessed as variables in an aggregate expression context (e.g. "$$var").
    ///
    /// Only available in MongoDB 5.0+.
    #[serde(rename = "let")]
    pub let_vars: Option<Document>,

    /// Tags the query with an arbitrary [`Bson`] value to help trace the operation through the
    /// database profiler, currentOp and logs.
    ///
    /// This option is only available on server versions 4.4+.
    pub comment: Option<Bson>,
}

/// Specifies the options to a
/// [`Collection::delete_one`](../struct.Collection.html#method.delete_one) or
/// [`Collection::delete_many`](../struct.Collection.html#method.delete_many) operation.
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, Default, Deserialize, TypedBuilder, Serialize)]
#[serde(rename_all = "camelCase")]
#[builder(field_defaults(default, setter(into)))]
#[non_exhaustive]
pub struct DeleteOptions {
    /// The collation to use for the operation.
    ///
    /// See the [documentation](https://www.mongodb.com/docs/manual/reference/collation/) for more
    /// information on how to use this option.
    pub collation: Option<Collation>,

    /// The write concern for the operation.
    pub write_concern: Option<WriteConcern>,

    /// The index to use for the operation.
    /// Only available in MongoDB 4.4+.
    pub hint: Option<Hint>,

    /// Map of parameter names and values. Values must be constant or closed
    /// expressions that do not reference document fields. Parameters can then be
    /// accessed as variables in an aggregate expression context (e.g. "$$var").
    ///
    /// Only available in MongoDB 5.0+.
    #[serde(rename = "let")]
    pub let_vars: Option<Document>,

    /// Tags the query with an arbitrary [`Bson`] value to help trace the operation through the
    /// database profiler, currentOp and logs.
    ///
    /// This option is only available on server versions 4.4+.
    pub comment: Option<Bson>,
}

/// Specifies the options to a
/// [`Collection::find_one_and_delete`](../struct.Collection.html#method.find_one_and_delete)
/// operation.
#[skip_serializing_none]
#[derive(Clone, Debug, Default, Deserialize, TypedBuilder)]
#[serde(rename_all = "camelCase")]
#[builder(field_defaults(default, setter(into)))]
#[non_exhaustive]
pub struct FindOneAndDeleteOptions {
    /// The maximum amount of time to allow the query to run.
    ///
    /// This options maps to the `maxTimeMS` MongoDB query option, so the duration will be sent
    /// across the wire as an integer number of milliseconds.
    pub max_time: Option<Duration>,

    /// Limits the fields of the document being returned.
    pub projection: Option<Document>,

    /// The order of the documents for the purposes of the operation.
    pub sort: Option<Document>,

    /// The level of the write concern
    pub write_concern: Option<WriteConcern>,

    /// The collation to use for the operation.
    ///
    /// See the [documentation](https://www.mongodb.com/docs/manual/reference/collation/) for more
    /// information on how to use this option.
    pub collation: Option<Collation>,

    /// The index to use for the operation.
    /// Only available in MongoDB 4.4+.
    pub hint: Option<Hint>,

    /// Map of parameter names and values. Values must be constant or closed
    /// expressions that do not reference document fields. Parameters can then be
    /// accessed as variables in an aggregate expression context (e.g. "$$var").
    ///
    /// Only available in MongoDB 5.0+.
    #[serde(rename = "let")]
    pub let_vars: Option<Document>,

    /// Tags the query with an arbitrary [`Bson`] value to help trace the operation through the
    /// database profiler, currentOp and logs.
    ///
    /// This option is only available on server versions 4.4+.
    pub comment: Option<Bson>,
}

/// Specifies the options to a
/// [`Collection::find_one_and_replace`](../struct.Collection.html#method.find_one_and_replace)
/// operation.
#[skip_serializing_none]
#[derive(Clone, Debug, Default, Deserialize, TypedBuilder)]
#[builder(field_defaults(default, setter(into)))]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct FindOneAndReplaceOptions {
    /// Opt out of document-level validation.
    pub bypass_document_validation: Option<bool>,

    /// The maximum amount of time to allow the query to run.
    ///
    /// This options maps to the `maxTimeMS` MongoDB query option, so the duration will be sent
    /// across the wire as an integer number of milliseconds.
    pub max_time: Option<Duration>,

    /// Limits the fields of the document being returned.
    pub projection: Option<Document>,

    /// Whether the operation should return the document before or after modification.
    pub return_document: Option<ReturnDocument>,

    /// The order of the documents for the purposes of the operation.
    pub sort: Option<Document>,

    /// If true, insert a document if no matching document is found.
    pub upsert: Option<bool>,

    /// The level of the write concern
    pub write_concern: Option<WriteConcern>,

    /// The collation to use for the operation.
    ///
    /// See the [documentation](https://www.mongodb.com/docs/manual/reference/collation/) for more
    /// information on how to use this option.
    pub collation: Option<Collation>,

    /// The index to use for the operation.
    /// Only available in MongoDB 4.4+.
    pub hint: Option<Hint>,

    /// Map of parameter names and values. Values must be constant or closed
    /// expressions that do not reference document fields. Parameters can then be
    /// accessed as variables in an aggregate expression context (e.g. "$$var").
    ///
    /// Only available in MongoDB 5.0+.
    #[serde(rename = "let")]
    pub let_vars: Option<Document>,

    /// Tags the query with an arbitrary [`Bson`] value to help trace the operation through the
    /// database profiler, currentOp and logs.
    ///
    /// This option is only available on server versions 4.4+.
    pub comment: Option<Bson>,
}

/// Specifies the options to a
/// [`Collection::find_one_and_update`](../struct.Collection.html#method.find_one_and_update)
/// operation.
#[skip_serializing_none]
#[derive(Clone, Debug, Default, Deserialize, TypedBuilder)]
#[serde(rename_all = "camelCase")]
#[builder(field_defaults(default, setter(into)))]
#[non_exhaustive]
pub struct FindOneAndUpdateOptions {
    /// A set of filters specifying to which array elements an update should apply.
    ///
    /// See the documentation [here](https://www.mongodb.com/docs/manual/reference/command/update/) for
    /// more information on array filters.
    pub array_filters: Option<Vec<Document>>,

    /// Opt out of document-level validation.
    pub bypass_document_validation: Option<bool>,

    /// The maximum amount of time to allow the query to run.
    ///
    /// This options maps to the `maxTimeMS` MongoDB query option, so the duration will be sent
    /// across the wire as an integer number of milliseconds.
    pub max_time: Option<Duration>,

    /// Limits the fields of the document being returned.
    pub projection: Option<Document>,

    /// Whether the operation should return the document before or after modification.
    pub return_document: Option<ReturnDocument>,

    /// The order of the documents for the purposes of the operation.
    pub sort: Option<Document>,

    /// If true, insert a document if no matching document is found.
    pub upsert: Option<bool>,

    /// The level of the write concern
    pub write_concern: Option<WriteConcern>,

    /// The collation to use for the operation.
    ///
    /// See the [documentation](https://www.mongodb.com/docs/manual/reference/collation/) for more
    /// information on how to use this option.
    pub collation: Option<Collation>,

    /// The index to use for the operation.
    /// Only available in MongoDB 4.4+.
    pub hint: Option<Hint>,

    /// Map of parameter names and values. Values must be constant or closed
    /// expressions that do not reference document fields. Parameters can then be
    /// accessed as variables in an aggregate expression context (e.g. "$$var").
    ///
    /// Only available in MongoDB 5.0+.
    #[serde(rename = "let")]
    pub let_vars: Option<Document>,

    /// Tags the query with an arbitrary [`Bson`] value to help trace the operation through the
    /// database profiler, currentOp and logs.
    ///
    /// This option is only available on server versions 4.4+.
    pub comment: Option<Bson>,
}

/// Specifies the options to a [`Collection::aggregate`](../struct.Collection.html#method.aggregate)
/// operation.
#[skip_serializing_none]
#[derive(Clone, Debug, Default, Deserialize, TypedBuilder, Serialize)]
#[serde(rename_all = "camelCase")]
#[builder(field_defaults(default, setter(into)))]
#[non_exhaustive]
pub struct AggregateOptions {
    /// Enables writing to temporary files. When set to true, aggregation stages can write data to
    /// the _tmp subdirectory in the dbPath directory.
    pub allow_disk_use: Option<bool>,

    /// The number of documents the server should return per cursor batch.
    ///
    /// Note that this does not have any affect on the documents that are returned by a cursor,
    /// only the number of documents kept in memory at a given time (and by extension, the
    /// number of round trips needed to return the entire set of documents returned by the
    /// query).
    #[serde(
        serialize_with = "serde_util::serialize_u32_option_as_batch_size",
        rename(serialize = "cursor")
    )]
    pub batch_size: Option<u32>,

    /// Opt out of document-level validation.
    pub bypass_document_validation: Option<bool>,

    /// The collation to use for the operation.
    ///
    /// See the [documentation](https://www.mongodb.com/docs/manual/reference/collation/) for more
    /// information on how to use this option.
    pub collation: Option<Collation>,

    /// Tags the query with an arbitrary string to help trace the operation through the
    /// database profiler, currentOp and logs.
    ///
    /// If both this option and `comment_bson` are specified, `comment_bson` will take precedence.
    // TODO RUST-1364: Update this field to be of type Option<Bson>
    #[serde(skip_serializing)]
    pub comment: Option<String>,

    /// Tags the query with an arbitrary [`Bson`] value to help trace the operation through the
    /// database profiler, currentOp and logs.
    ///
    /// This option is only supported on server versions 4.4+. Use the `comment` option on
    /// older server versions.
    // TODO RUST-1364: Remove this field
    #[serde(rename(serialize = "comment"))]
    pub comment_bson: Option<Bson>,

    /// The index to use for the operation.
    pub hint: Option<Hint>,

    /// The maximum amount of time for the server to wait on new documents to satisfy a tailable
    /// await cursor query.
    ///
    /// This option will have no effect on non-tailable cursors that result from this operation.
    #[serde(
        skip_serializing,
        deserialize_with = "serde_util::deserialize_duration_option_from_u64_millis",
        default
    )]
    pub max_await_time: Option<Duration>,

    /// The maximum amount of time to allow the query to run.
    ///
    /// This options maps to the `maxTimeMS` MongoDB query option, so the duration will be sent
    /// across the wire as an integer number of milliseconds.
    #[serde(
        serialize_with = "serde_util::serialize_duration_option_as_int_millis",
        rename = "maxTimeMS",
        deserialize_with = "serde_util::deserialize_duration_option_from_u64_millis",
        default
    )]
    pub max_time: Option<Duration>,

    /// The read concern to use for the operation.
    ///
    /// If none is specified, the read concern defined on the object executing this operation will
    /// be used.
    #[serde(skip_serializing)]
    pub read_concern: Option<ReadConcern>,

    /// The criteria used to select a server for this operation.
    ///
    /// If none is specified, the selection criteria defined on the object executing this operation
    /// will be used.
    #[serde(skip_serializing)]
    #[serde(rename = "readPreference")]
    pub selection_criteria: Option<SelectionCriteria>,

    /// The write concern to use for the operation.
    ///
    /// If none is specified, the write concern defined on the object executing this operation will
    /// be used.
    pub write_concern: Option<WriteConcern>,

    /// A document with any amount of parameter names, each followed by definitions of constants in
    /// the MQL Aggregate Expression language.  Each parameter name is then usable to access the
    /// value of the corresponding MQL Expression with the "$$" syntax within Aggregate Expression
    /// contexts.
    ///
    /// This feature is only available on server versions 5.0 and above.
    #[serde(rename = "let")]
    pub let_vars: Option<Document>,
}

/// Specifies the options to a
/// [`Collection::count_documents`](../struct.Collection.html#method.count_documents) operation.
#[skip_serializing_none]
#[derive(Clone, Debug, Default, Deserialize, TypedBuilder)]
#[serde(rename_all = "camelCase")]
#[builder(field_defaults(default, setter(into)))]
#[non_exhaustive]
pub struct CountOptions {
    /// The index to use for the operation.
    pub hint: Option<Hint>,

    /// The maximum number of documents to count.
    pub limit: Option<u64>,

    /// The maximum amount of time to allow the query to run.
    ///
    /// This options maps to the `maxTimeMS` MongoDB query option, so the duration will be sent
    /// across the wire as an integer number of milliseconds.
    #[serde(
        default,
        deserialize_with = "serde_util::deserialize_duration_option_from_u64_millis"
    )]
    pub max_time: Option<Duration>,

    /// The number of documents to skip before counting.
    pub skip: Option<u64>,

    /// The collation to use for the operation.
    ///
    /// See the [documentation](https://www.mongodb.com/docs/manual/reference/collation/) for more
    /// information on how to use this option.
    pub collation: Option<Collation>,

    /// The criteria used to select a server for this operation.
    ///
    /// If none specified, the default set on the collection will be used.
    pub selection_criteria: Option<SelectionCriteria>,

    /// The level of the read concern.
    #[serde(skip_serializing)]
    pub read_concern: Option<ReadConcern>,

    /// Tags the query with an arbitrary [`Bson`] value to help trace the operation through the
    /// database profiler, currentOp and logs.
    ///
    /// This option is only available on server versions 4.4+.
    pub comment: Option<Bson>,
}

// rustfmt tries to split the link up when it's all on one line, which breaks the link, so we wrap
// the link contents in whitespace to get it to render correctly.
//
/// Specifies the options to a
/// [
///  `Collection::estimated_document_count`
/// ](../struct.Collection.html#method.estimated_document_count) operation.
#[serde_with::skip_serializing_none]
#[derive(Debug, Default, Deserialize, TypedBuilder, Serialize, Clone)]
#[serde(rename_all = "camelCase")]
#[builder(field_defaults(default, setter(into)))]
#[non_exhaustive]
pub struct EstimatedDocumentCountOptions {
    /// The maximum amount of time to allow the query to run.
    ///
    /// This options maps to the `maxTimeMS` MongoDB query option, so the duration will be sent
    /// across the wire as an integer number of milliseconds.
    #[serde(
        default,
        serialize_with = "serde_util::serialize_duration_option_as_int_millis",
        rename = "maxTimeMS",
        deserialize_with = "serde_util::deserialize_duration_option_from_u64_millis"
    )]
    pub max_time: Option<Duration>,

    /// The criteria used to select a server for this operation.
    ///
    /// If none specified, the default set on the collection will be used.
    #[serde(skip_serializing)]
    pub selection_criteria: Option<SelectionCriteria>,

    /// The level of the read concern.
    #[serde(skip_serializing)]
    pub read_concern: Option<ReadConcern>,

    /// Tags the query with an arbitrary [`Bson`] value to help trace the operation through the
    /// database profiler, currentOp and logs.
    ///
    /// This option is only supported on server versions 4.4+. The comment can be any [`Bson`]
    /// value on server versions 4.4.14+. On server versions between 4.4.0 and 4.4.14, only
    /// [`Bson::String`] values are supported.
    pub comment: Option<Bson>,
}

/// Specifies the options to a [`Collection::distinct`](../struct.Collection.html#method.distinct)
/// operation.
#[serde_with::skip_serializing_none]
#[derive(Debug, Default, Deserialize, TypedBuilder, Serialize, Clone)]
#[builder(field_defaults(default, setter(into)))]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct DistinctOptions {
    /// The maximum amount of time to allow the query to run.
    ///
    /// This options maps to the `maxTimeMS` MongoDB query option, so the duration will be sent
    /// across the wire as an integer number of milliseconds.
    #[serde(
        default,
        serialize_with = "serde_util::serialize_duration_option_as_int_millis",
        rename = "maxTimeMS",
        deserialize_with = "serde_util::deserialize_duration_option_from_u64_millis"
    )]
    pub max_time: Option<Duration>,

    /// The criteria used to select a server for this operation.
    ///
    /// If none specified, the default set on the collection will be used.
    #[serde(skip_serializing)]
    pub selection_criteria: Option<SelectionCriteria>,

    /// The level of the read concern.
    #[serde(skip_serializing)]
    pub read_concern: Option<ReadConcern>,

    /// The collation to use for the operation.
    ///
    /// See the [documentation](https://www.mongodb.com/docs/manual/reference/collation/) for more
    /// information on how to use this option.
    pub collation: Option<Collation>,

    /// Tags the query with an arbitrary [`Bson`] value to help trace the operation through the
    /// database profiler, currentOp and logs.
    ///
    /// This option is only available on server versions 4.4+.
    pub comment: Option<Bson>,
}

/// Specifies the options to a [`Collection::find`](../struct.Collection.html#method.find)
/// operation.
#[skip_serializing_none]
#[derive(Clone, Debug, Default, Deserialize, TypedBuilder, Serialize)]
#[builder(field_defaults(default, setter(into)))]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct FindOptions {
    /// Enables writing to temporary files by the server. When set to true, the find operation can
    /// write data to the _tmp subdirectory in the dbPath directory. Only supported in server
    /// versions 4.4+.
    pub allow_disk_use: Option<bool>,

    /// If true, partial results will be returned from a mongos rather than an error being
    /// returned if one or more shards is down.
    pub allow_partial_results: Option<bool>,

    /// The number of documents the server should return per cursor batch.
    ///
    /// Note that this does not have any affect on the documents that are returned by a cursor,
    /// only the number of documents kept in memory at a given time (and by extension, the
    /// number of round trips needed to return the entire set of documents returned by the
    /// query.
    #[serde(serialize_with = "serde_util::serialize_u32_option_as_i32")]
    pub batch_size: Option<u32>,

    /// Tags the query with an arbitrary string to help trace the operation through the
    /// database profiler, currentOp and logs.
    ///
    /// If both this option and `comment_bson` are specified, `comment_bson` will take precedence.
    // TODO RUST-1364: Update this field to be of type Option<Bson>
    #[serde(skip_serializing)]
    pub comment: Option<String>,

    /// Tags the query with an arbitrary [`Bson`] value to help trace the operation through the
    /// database profiler, currentOp and logs.
    ///
    /// This option is only supported on server versions 4.4+. Use the `comment` option on
    /// older server versions.
    // TODO RUST-1364: Remove this field
    #[serde(rename(serialize = "comment"))]
    pub comment_bson: Option<Bson>,

    /// The type of cursor to return.
    #[serde(skip)]
    pub cursor_type: Option<CursorType>,

    /// The index to use for the operation.
    pub hint: Option<Hint>,

    /// The maximum number of documents to query.
    /// If a negative number is specified, the documents will be returned in a single batch limited
    /// in number by the positive value of the specified limit.
    #[serde(serialize_with = "serialize_absolute_value")]
    pub limit: Option<i64>,

    /// The exclusive upper bound for a specific index.
    pub max: Option<Document>,

    /// The maximum amount of time for the server to wait on new documents to satisfy a tailable
    /// cursor query. If the cursor is not tailable, this option is ignored.
    #[serde(skip)]
    pub max_await_time: Option<Duration>,

    /// Maximum number of documents or index keys to scan when executing the query.
    ///
    /// Note: this option is deprecated starting in MongoDB version 4.0 and removed in MongoDB 4.2.
    /// Use the maxTimeMS option instead.
    #[serde(serialize_with = "serde_util::serialize_u64_option_as_i64")]
    pub max_scan: Option<u64>,

    /// The maximum amount of time to allow the query to run.
    ///
    /// This options maps to the `maxTimeMS` MongoDB query option, so the duration will be sent
    /// across the wire as an integer number of milliseconds.
    #[serde(
        rename = "maxTimeMS",
        serialize_with = "serde_util::serialize_duration_option_as_int_millis"
    )]
    pub max_time: Option<Duration>,

    /// The inclusive lower bound for a specific index.
    pub min: Option<Document>,

    /// Whether the server should close the cursor after a period of inactivity.
    pub no_cursor_timeout: Option<bool>,

    /// Limits the fields of the document being returned.
    pub projection: Option<Document>,

    /// The read concern to use for this find query.
    ///
    /// If none specified, the default set on the collection will be used.
    #[serde(skip_serializing)]
    pub read_concern: Option<ReadConcern>,

    /// Whether to return only the index keys in the documents.
    pub return_key: Option<bool>,

    /// The criteria used to select a server for this find query.
    ///
    /// If none specified, the default set on the collection will be used.
    #[serde(skip)]
    pub selection_criteria: Option<SelectionCriteria>,

    /// Whether to return the record identifier for each document.
    pub show_record_id: Option<bool>,

    /// The number of documents to skip before counting.
    #[serde(serialize_with = "serde_util::serialize_u64_option_as_i64")]
    pub skip: Option<u64>,

    /// The order of the documents for the purposes of the operation.
    pub sort: Option<Document>,

    /// The collation to use for the operation.
    ///
    /// See the [documentation](https://www.mongodb.com/docs/manual/reference/collation/) for more
    /// information on how to use this option.
    pub collation: Option<Collation>,

    /// Map of parameter names and values. Values must be constant or closed
    /// expressions that do not reference document fields. Parameters can then be
    /// accessed as variables in an aggregate expression context (e.g. "$$var").
    ///
    /// Only available in MongoDB 5.0+.
    #[serde(rename = "let")]
    pub let_vars: Option<Document>,
}

impl From<FindOneOptions> for FindOptions {
    fn from(options: FindOneOptions) -> Self {
        FindOptions {
            allow_disk_use: None,
            allow_partial_results: options.allow_partial_results,
            collation: options.collation,
            comment: options.comment,
            comment_bson: options.comment_bson,
            hint: options.hint,
            max: options.max,
            max_scan: options.max_scan,
            max_time: options.max_time,
            min: options.min,
            projection: options.projection,
            read_concern: options.read_concern,
            return_key: options.return_key,
            selection_criteria: options.selection_criteria,
            show_record_id: options.show_record_id,
            skip: options.skip,
            batch_size: None,
            cursor_type: None,
            limit: Some(-1),
            max_await_time: None,
            no_cursor_timeout: None,
            sort: options.sort,
            let_vars: options.let_vars,
        }
    }
}

/// Custom serializer used to serialize limit as its absolute value.
fn serialize_absolute_value<S>(
    val: &Option<i64>,
    serializer: S,
) -> std::result::Result<S::Ok, S::Error>
where
    S: Serializer,
{
    match val {
        Some(v) => serializer.serialize_i64(v.abs()),
        None => serializer.serialize_none(),
    }
}

/// Specifies the options to a [`Collection::find_one`](../struct.Collection.html#method.find_one)
/// operation.
#[derive(Clone, Debug, Default, Deserialize, TypedBuilder)]
#[serde(rename_all = "camelCase")]
#[builder(field_defaults(default, setter(into)))]
#[non_exhaustive]
pub struct FindOneOptions {
    /// If true, partial results will be returned from a mongos rather than an error being
    /// returned if one or more shards is down.
    pub allow_partial_results: Option<bool>,

    /// The collation to use for the operation.
    ///
    /// See the [documentation](https://www.mongodb.com/docs/manual/reference/collation/) for more
    /// information on how to use this option.
    pub collation: Option<Collation>,

    /// Tags the query with an arbitrary string value to help trace the operation through the
    /// database profiler, currentOp and logs.
    ///
    /// If both this option and `comment_bson` are specified, `comment_bson` will take precedence.
    // TODO RUST-1364: Update this field to be of type Option<Bson>
    pub comment: Option<String>,

    /// Tags the query with an arbitrary [`Bson`] value to help trace the operation through the
    /// database profiler, currentOp and logs.
    ///
    /// This option is only supported on server versions 4.4+. Use the `comment` option on
    /// older server versions.
    // TODO RUST-1364: Remove this field
    pub comment_bson: Option<Bson>,

    /// The index to use for the operation.
    pub hint: Option<Hint>,

    /// The exclusive upper bound for a specific index.
    pub max: Option<Document>,

    /// Maximum number of documents or index keys to scan when executing the query.
    ///
    /// Note: this option is deprecated starting in MongoDB version 4.0 and removed in MongoDB 4.2.
    /// Use the maxTimeMS option instead.
    #[serde(serialize_with = "bson_util::serialize_u64_option_as_i64")]
    pub max_scan: Option<u64>,

    /// The maximum amount of time to allow the query to run.
    ///
    /// This options maps to the `maxTimeMS` MongoDB query option, so the duration will be sent
    /// across the wire as an integer number of milliseconds.
    #[serde(
        default,
        deserialize_with = "serde_util::deserialize_duration_option_from_u64_millis"
    )]
    pub max_time: Option<Duration>,

    /// The inclusive lower bound for a specific index.
    pub min: Option<Document>,

    /// Limits the fields of the document being returned.
    pub projection: Option<Document>,

    /// The read concern to use for this find query.
    ///
    /// If none specified, the default set on the collection will be used.
    #[serde(skip_serializing)]
    pub read_concern: Option<ReadConcern>,

    /// Whether to return only the index keys in the documents.
    pub return_key: Option<bool>,

    /// The criteria used to select a server for this find query.
    ///
    /// If none specified, the default set on the collection will be used.
    pub selection_criteria: Option<SelectionCriteria>,

    /// Whether to return the record identifier for each document.
    pub show_record_id: Option<bool>,

    /// The number of documents to skip before counting.
    #[serde(serialize_with = "bson_util::serialize_u64_option_as_i64")]
    pub skip: Option<u64>,

    /// The order of the documents for the purposes of the operation.
    pub sort: Option<Document>,

    /// Map of parameter names and values. Values must be constant or closed
    /// expressions that do not reference document fields. Parameters can then be
    /// accessed as variables in an aggregate expression context (e.g. "$$var").
    ///
    /// Only available in MongoDB 5.0+.
    #[serde(rename = "let")]
    pub let_vars: Option<Document>,
}

/// Specifies the options to a
/// [`Collection::create_index`](../struct.Collection.html#method.create_index) or [`Collection::
/// create_indexes`](../struct.Collection.html#method.create_indexes) operation.
///
/// For more information, see [`createIndexes`](https://www.mongodb.com/docs/manual/reference/command/createIndexes/).
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, Default, TypedBuilder, Serialize)]
#[builder(field_defaults(default, setter(into)))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[non_exhaustive]
pub struct CreateIndexOptions {
    /// Specify the commit quorum needed to mark an `index` as ready.
    pub commit_quorum: Option<CommitQuorum>,

    /// The maximum amount of time to allow the index to build.
    ///
    /// This option maps to the `maxTimeMS` MongoDB query option, so the duration will be sent
    /// across the wire as an integer number of milliseconds.
    #[serde(
        rename = "maxTimeMS",
        default,
        serialize_with = "serde_util::serialize_duration_option_as_int_millis",
        deserialize_with = "serde_util::deserialize_duration_option_from_u64_millis"
    )]
    pub max_time: Option<Duration>,

    /// The write concern for the operation.
    pub write_concern: Option<WriteConcern>,

    /// Tags the query with an arbitrary [`Bson`] value to help trace the operation through the
    /// database profiler, currentOp and logs.
    ///
    /// This option is only available on server versions 4.4+.
    pub comment: Option<Bson>,
}

/// Specifies the options to a [`Collection::drop`](../struct.Collection.html#method.drop)
/// operation.
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, Default, Deserialize, TypedBuilder, Serialize)]
#[serde(rename_all = "camelCase")]
#[builder(field_defaults(default, setter(into)))]
#[non_exhaustive]
pub struct DropCollectionOptions {
    /// The write concern for the operation.
    pub write_concern: Option<WriteConcern>,

    /// Map of encrypted fields for the collection.
    // Serialization is skipped because the server doesn't accept this option; it's needed for
    // preprocessing.  Deserialization needs to remain because it's used in test files.
    #[cfg(feature = "in-use-encryption-unstable")]
    #[serde(skip_serializing)]
    pub encrypted_fields: Option<Document>,
}

/// Specifies the options to a
/// [`Collection::drop_index`](../struct.Collection.html#method.drop_index) or
/// [`Collection::drop_indexes`](../struct.Collection.html#method.drop_indexes) operation.
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, Default, Deserialize, TypedBuilder, Serialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[builder(field_defaults(default, setter(into)))]
#[non_exhaustive]
pub struct DropIndexOptions {
    /// The maximum amount of time to allow the index to drop.
    ///
    /// This option maps to the `maxTimeMS` MongoDB query option, so the duration will be sent
    /// across the wire as an integer number of milliseconds.
    #[serde(
        rename = "maxTimeMS",
        default,
        serialize_with = "serde_util::serialize_duration_option_as_int_millis",
        deserialize_with = "serde_util::deserialize_duration_option_from_u64_millis"
    )]
    pub max_time: Option<Duration>,

    /// The write concern for the operation.
    pub write_concern: Option<WriteConcern>,

    /// Tags the query with an arbitrary [`Bson`] value to help trace the operation through the
    /// database profiler, currentOp and logs.
    ///
    /// This option is only available on server versions 4.4+.
    pub comment: Option<Bson>,
}

/// Specifies the options to a
/// [`Collection::list_indexes`](../struct.Collection.html#method.list_indexes) operation.
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, Default, Deserialize, TypedBuilder, Serialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[builder(field_defaults(default, setter(into)))]
#[non_exhaustive]
pub struct ListIndexesOptions {
    /// The maximum amount of time to search for the index.
    ///
    /// This option maps to the `maxTimeMS` MongoDB query option, so the duration will be sent
    /// across the wire as an integer number of milliseconds.
    #[serde(
        rename = "maxTimeMS",
        default,
        serialize_with = "serde_util::serialize_duration_option_as_int_millis",
        deserialize_with = "serde_util::deserialize_duration_option_from_u64_millis"
    )]
    pub max_time: Option<Duration>,

    /// The number of indexes the server should return per cursor batch.
    #[serde(default, skip_serializing)]
    pub batch_size: Option<u32>,

    /// Tags the query with an arbitrary [`Bson`] value to help trace the operation through the
    /// database profiler, currentOp and logs.
    ///
    /// This option is only available on server versions 4.4+.
    pub comment: Option<Bson>,
}

/// The minimum number of data-bearing voting replica set members (i.e. commit quorum), including
/// the primary, that must report a successful index build before the primary marks the indexes as
/// ready.
///
/// For more information, see the [documentation](https://www.mongodb.com/docs/manual/reference/command/createIndexes/#definition)
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum CommitQuorum {
    /// A specific number of voting replica set members. When set to 0, disables quorum voting.
    Nodes(u32),

    /// All data-bearing voting replica set members (default).
    VotingMembers,

    /// A simple majority of voting members.
    Majority,

    /// A replica set tag name.
    Custom(String),
}

impl Serialize for CommitQuorum {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match self {
            CommitQuorum::Nodes(n) => serde_helpers::serialize_u32_as_i32(n, serializer),
            CommitQuorum::VotingMembers => serializer.serialize_str("votingMembers"),
            CommitQuorum::Majority => serializer.serialize_str("majority"),
            CommitQuorum::Custom(s) => serializer.serialize_str(s),
        }
    }
}

impl<'de> Deserialize<'de> for CommitQuorum {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        #[derive(Deserialize)]
        #[serde(untagged)]
        enum IntOrString {
            Int(u32),
            String(String),
        }
        match IntOrString::deserialize(deserializer)? {
            IntOrString::String(s) => {
                if s == "votingMembers" {
                    Ok(CommitQuorum::VotingMembers)
                } else if s == "majority" {
                    Ok(CommitQuorum::Majority)
                } else {
                    Ok(CommitQuorum::Custom(s))
                }
            }
            IntOrString::Int(i) => Ok(CommitQuorum::Nodes(i)),
        }
    }
}