mongodb/coll/
options.rs

1use std::time::Duration;
2
3use macro_magic::export_tokens;
4use serde::{de::Error, Deserialize, Deserializer, Serialize, Serializer};
5use serde_with::skip_serializing_none;
6use typed_builder::TypedBuilder;
7
8use crate::{
9    bson::{doc, Bson, Document, RawBson, RawDocumentBuf},
10    concern::{ReadConcern, WriteConcern},
11    error::Result,
12    options::Collation,
13    selection_criteria::SelectionCriteria,
14    serde_util::{self, write_concern_is_empty},
15};
16
17/// These are the valid options for creating a [`Collection`](crate::Collection) with
18/// [`Database::collection_with_options`](crate::Database::collection_with_options).
19#[derive(Clone, Debug, Default, Deserialize, TypedBuilder)]
20#[builder(field_defaults(default, setter(into)))]
21#[serde(rename_all = "camelCase")]
22#[non_exhaustive]
23pub struct CollectionOptions {
24    /// The default read preference for operations.
25    pub selection_criteria: Option<SelectionCriteria>,
26
27    /// The default read concern for operations.
28    pub read_concern: Option<ReadConcern>,
29
30    /// The default write concern for operations.
31    pub write_concern: Option<WriteConcern>,
32}
33
34/// Specifies whether a
35/// [`Collection::find_one_and_replace`](../struct.Collection.html#method.find_one_and_replace) and
36/// [`Collection::find_one_and_update`](../struct.Collection.html#method.find_one_and_update)
37/// operation should return the document before or after modification.
38#[derive(Clone, Debug)]
39#[non_exhaustive]
40pub enum ReturnDocument {
41    /// Return the document after modification.
42    After,
43    /// Return the document before modification.
44    Before,
45}
46
47impl ReturnDocument {
48    pub(crate) fn as_bool(&self) -> bool {
49        match self {
50            ReturnDocument::After => true,
51            ReturnDocument::Before => false,
52        }
53    }
54}
55
56impl<'de> Deserialize<'de> for ReturnDocument {
57    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> std::result::Result<Self, D::Error> {
58        let s = String::deserialize(deserializer)?;
59        match s.to_lowercase().as_str() {
60            "after" => Ok(ReturnDocument::After),
61            "before" => Ok(ReturnDocument::Before),
62            other => Err(D::Error::custom(format!(
63                "Unknown return document value: {other}"
64            ))),
65        }
66    }
67}
68
69/// Specifies the index to use for an operation.
70#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
71#[serde(untagged)]
72#[non_exhaustive]
73pub enum Hint {
74    /// Specifies the keys of the index to use.
75    Keys(Document),
76    /// Specifies the name of the index to use.
77    Name(String),
78}
79
80impl Hint {
81    pub(crate) fn to_raw_bson(&self) -> Result<RawBson> {
82        Ok(match self {
83            Hint::Keys(ref d) => RawBson::Document(RawDocumentBuf::try_from(d)?),
84            Hint::Name(ref s) => RawBson::String(s.clone()),
85        })
86    }
87}
88
89/// Specifies the type of cursor to return from a find operation.
90#[derive(Debug, Clone, Copy, Deserialize)]
91#[serde(rename_all = "camelCase")]
92#[non_exhaustive]
93pub enum CursorType {
94    /// Default; close the cursor after the last document is received from the server.
95    NonTailable,
96
97    /// Do not close the cursor after the last document is received from the server. If more
98    /// results become available later, the cursor will return them.
99    Tailable,
100
101    /// Similar to `Tailable`, except that the cursor should block on receiving more results if
102    /// none are available.
103    TailableAwait,
104}
105
106/// Specifies the options to a
107/// [`Collection::insert_one`](../struct.Collection.html#method.insert_one) operation.
108#[skip_serializing_none]
109#[derive(Clone, Debug, Default, Deserialize, TypedBuilder)]
110#[serde(rename_all = "camelCase")]
111#[builder(field_defaults(default, setter(into)))]
112#[non_exhaustive]
113#[export_tokens]
114pub struct InsertOneOptions {
115    /// Opt out of document-level validation.
116    pub bypass_document_validation: Option<bool>,
117
118    /// The write concern for the operation.
119    #[serde(skip_serializing_if = "write_concern_is_empty")]
120    pub write_concern: Option<WriteConcern>,
121
122    /// Tags the query with an arbitrary [`Bson`] value to help trace the operation through the
123    /// database profiler, currentOp and logs.
124    ///
125    /// This option is only available on server versions 4.4+.
126    pub comment: Option<Bson>,
127}
128
129/// Specifies the options to a
130/// [`Collection::insert_many`](../struct.Collection.html#method.insert_many) operation.
131#[skip_serializing_none]
132#[derive(Clone, Debug, Default, TypedBuilder, Serialize, Deserialize)]
133#[builder(field_defaults(default, setter(into)))]
134#[serde(rename_all = "camelCase")]
135#[non_exhaustive]
136#[export_tokens]
137pub struct InsertManyOptions {
138    /// Opt out of document-level validation.
139    pub bypass_document_validation: Option<bool>,
140
141    /// If true, when an insert fails, return without performing the remaining writes. If false,
142    /// when a write fails, continue with the remaining writes, if any.
143    ///
144    /// Defaults to true.
145    pub ordered: Option<bool>,
146
147    /// The write concern for the operation.
148    #[serde(skip_deserializing, skip_serializing_if = "write_concern_is_empty")]
149    pub write_concern: Option<WriteConcern>,
150
151    /// Tags the query with an arbitrary [`Bson`] value to help trace the operation through the
152    /// database profiler, currentOp and logs.
153    ///
154    /// This option is only available on server versions 4.4+.
155    pub comment: Option<Bson>,
156}
157
158impl InsertManyOptions {
159    pub(crate) fn from_insert_one_options(options: InsertOneOptions) -> Self {
160        Self {
161            bypass_document_validation: options.bypass_document_validation,
162            ordered: None,
163            write_concern: options.write_concern,
164            comment: options.comment,
165        }
166    }
167}
168
169/// Enum modeling the modifications to apply during an update.
170/// For details, see the official MongoDB
171/// [documentation](https://www.mongodb.com/docs/manual/reference/command/update/#update-command-behaviors)
172#[derive(Clone, Debug, Deserialize, Serialize)]
173#[serde(untagged)]
174#[non_exhaustive]
175pub enum UpdateModifications {
176    /// A document that contains only update operator expressions.
177    Document(Document),
178
179    /// An aggregation pipeline.
180    Pipeline(Vec<Document>),
181}
182
183impl From<Document> for UpdateModifications {
184    fn from(item: Document) -> Self {
185        UpdateModifications::Document(item)
186    }
187}
188
189impl From<Vec<Document>> for UpdateModifications {
190    fn from(item: Vec<Document>) -> Self {
191        UpdateModifications::Pipeline(item)
192    }
193}
194
195/// Specifies the options to a
196/// [`Collection::update_one`](../struct.Collection.html#method.update_one) or
197/// [`Collection::update_many`](../struct.Collection.html#method.update_many) operation.
198#[skip_serializing_none]
199#[derive(Clone, Debug, Default, Deserialize, TypedBuilder)]
200#[serde(rename_all = "camelCase")]
201#[builder(field_defaults(default, setter(into)))]
202#[non_exhaustive]
203#[export_tokens]
204pub struct UpdateOptions {
205    /// A set of filters specifying to which array elements an update should apply.
206    ///
207    /// See the documentation [here](https://www.mongodb.com/docs/manual/reference/command/update/) for
208    /// more information on array filters.
209    pub array_filters: Option<Vec<Document>>,
210
211    /// Opt out of document-level validation.
212    pub bypass_document_validation: Option<bool>,
213
214    /// If true, insert a document if no matching document is found.
215    pub upsert: Option<bool>,
216
217    /// The collation to use for the operation.
218    ///
219    /// See the [documentation](https://www.mongodb.com/docs/manual/reference/collation/) for more
220    /// information on how to use this option.
221    pub collation: Option<Collation>,
222
223    /// A document or string that specifies the index to use to support the query predicate.
224    ///
225    /// See the official MongoDB
226    /// [documentation](https://www.mongodb.com/docs/manual/reference/command/update/#ex-update-command-hint) for examples.
227    pub hint: Option<Hint>,
228
229    /// The write concern for the operation.
230    pub write_concern: Option<WriteConcern>,
231
232    /// Map of parameter names and values. Values must be constant or closed
233    /// expressions that do not reference document fields. Parameters can then be
234    /// accessed as variables in an aggregate expression context (e.g. "$$var").
235    ///
236    /// Only available in MongoDB 5.0+.
237    #[serde(rename = "let")]
238    pub let_vars: Option<Document>,
239
240    /// Tags the query with an arbitrary [`Bson`] value to help trace the operation through the
241    /// database profiler, currentOp and logs.
242    ///
243    /// This option is only available on server versions 4.4+.
244    pub comment: Option<Bson>,
245
246    /// Specify which document the operation updates if the query matches multiple
247    /// documents. The first document matched by the sort order will be updated.
248    ///
249    /// Only available in MongoDB 8.0+.
250    pub sort: Option<Document>,
251}
252
253impl UpdateOptions {
254    pub(crate) fn from_replace_options(options: ReplaceOptions) -> Self {
255        Self {
256            bypass_document_validation: options.bypass_document_validation,
257            upsert: options.upsert,
258            hint: options.hint,
259            write_concern: options.write_concern,
260            collation: options.collation,
261            let_vars: options.let_vars,
262            comment: options.comment,
263            sort: options.sort,
264            ..Default::default()
265        }
266    }
267}
268
269/// Specifies the options to a
270/// [`Collection::replace_one`](../struct.Collection.html#method.replace_one) operation.
271#[skip_serializing_none]
272#[derive(Clone, Debug, Default, Deserialize, TypedBuilder)]
273#[serde(rename_all = "camelCase")]
274#[builder(field_defaults(default, setter(into)))]
275#[non_exhaustive]
276#[export_tokens]
277pub struct ReplaceOptions {
278    /// Opt out of document-level validation.
279    pub bypass_document_validation: Option<bool>,
280
281    /// If true, insert a document if no matching document is found.
282    pub upsert: Option<bool>,
283
284    /// The collation to use for the operation.
285    ///
286    /// See the [documentation](https://www.mongodb.com/docs/manual/reference/collation/) for more
287    /// information on how to use this option.
288    pub collation: Option<Collation>,
289
290    /// A document or string that specifies the index to use to support the query predicate.
291    ///
292    /// See the official MongoDB
293    /// [documentation](https://www.mongodb.com/docs/manual/reference/command/update/#ex-update-command-hint) for examples.
294    pub hint: Option<Hint>,
295
296    /// The write concern for the operation.
297    #[serde(skip_serializing_if = "write_concern_is_empty")]
298    pub write_concern: Option<WriteConcern>,
299
300    /// Map of parameter names and values. Values must be constant or closed
301    /// expressions that do not reference document fields. Parameters can then be
302    /// accessed as variables in an aggregate expression context (e.g. "$$var").
303    ///
304    /// Only available in MongoDB 5.0+.
305    #[serde(rename = "let")]
306    pub let_vars: Option<Document>,
307
308    /// Tags the query with an arbitrary [`Bson`] value to help trace the operation through the
309    /// database profiler, currentOp and logs.
310    ///
311    /// This option is only available on server versions 4.4+.
312    pub comment: Option<Bson>,
313
314    /// Specify which document the operation replaces if the query matches multiple
315    /// documents. The first document matched by the sort order will be replaced.
316    ///
317    /// Only available in MongoDB 8.0+.
318    pub sort: Option<Document>,
319}
320
321/// Specifies the options to a
322/// [`Collection::delete_one`](../struct.Collection.html#method.delete_one) or
323/// [`Collection::delete_many`](../struct.Collection.html#method.delete_many) operation.
324#[serde_with::skip_serializing_none]
325#[derive(Clone, Debug, Default, Deserialize, TypedBuilder, Serialize)]
326#[serde(rename_all = "camelCase")]
327#[builder(field_defaults(default, setter(into)))]
328#[non_exhaustive]
329#[export_tokens]
330pub struct DeleteOptions {
331    /// The collation to use for the operation.
332    ///
333    /// See the [documentation](https://www.mongodb.com/docs/manual/reference/collation/) for more
334    /// information on how to use this option.
335    pub collation: Option<Collation>,
336
337    /// The write concern for the operation.
338    #[serde(skip_serializing_if = "write_concern_is_empty")]
339    pub write_concern: Option<WriteConcern>,
340
341    /// The index to use for the operation.
342    /// Only available in MongoDB 4.4+.
343    pub hint: Option<Hint>,
344
345    /// Map of parameter names and values. Values must be constant or closed
346    /// expressions that do not reference document fields. Parameters can then be
347    /// accessed as variables in an aggregate expression context (e.g. "$$var").
348    ///
349    /// Only available in MongoDB 5.0+.
350    #[serde(rename = "let")]
351    pub let_vars: Option<Document>,
352
353    /// Tags the query with an arbitrary [`Bson`] value to help trace the operation through the
354    /// database profiler, currentOp and logs.
355    ///
356    /// This option is only available on server versions 4.4+.
357    pub comment: Option<Bson>,
358}
359
360/// Specifies the options to a
361/// [`Collection::find_one_and_delete`](../struct.Collection.html#method.find_one_and_delete)
362/// operation.
363#[skip_serializing_none]
364#[derive(Clone, Debug, Default, Deserialize, TypedBuilder)]
365#[serde(rename_all = "camelCase")]
366#[builder(field_defaults(default, setter(into)))]
367#[non_exhaustive]
368#[export_tokens]
369pub struct FindOneAndDeleteOptions {
370    /// The maximum amount of time to allow the query to run.
371    ///
372    /// This options maps to the `maxTimeMS` MongoDB query option, so the duration will be sent
373    /// across the wire as an integer number of milliseconds.
374    pub max_time: Option<Duration>,
375
376    /// Limits the fields of the document being returned.
377    pub projection: Option<Document>,
378
379    /// The order of the documents for the purposes of the operation.
380    pub sort: Option<Document>,
381
382    /// The level of the write concern
383    #[serde(skip_serializing_if = "write_concern_is_empty")]
384    pub write_concern: Option<WriteConcern>,
385
386    /// The collation to use for the operation.
387    ///
388    /// See the [documentation](https://www.mongodb.com/docs/manual/reference/collation/) for more
389    /// information on how to use this option.
390    pub collation: Option<Collation>,
391
392    /// The index to use for the operation.
393    /// Only available in MongoDB 4.4+.
394    pub hint: Option<Hint>,
395
396    /// Map of parameter names and values. Values must be constant or closed
397    /// expressions that do not reference document fields. Parameters can then be
398    /// accessed as variables in an aggregate expression context (e.g. "$$var").
399    ///
400    /// Only available in MongoDB 5.0+.
401    #[serde(rename = "let")]
402    pub let_vars: Option<Document>,
403
404    /// Tags the query with an arbitrary [`Bson`] value to help trace the operation through the
405    /// database profiler, currentOp and logs.
406    ///
407    /// This option is only available on server versions 4.4+.
408    pub comment: Option<Bson>,
409}
410
411/// Specifies the options to a
412/// [`Collection::find_one_and_replace`](../struct.Collection.html#method.find_one_and_replace)
413/// operation.
414#[skip_serializing_none]
415#[derive(Clone, Debug, Default, Deserialize, TypedBuilder)]
416#[builder(field_defaults(default, setter(into)))]
417#[serde(rename_all = "camelCase")]
418#[non_exhaustive]
419#[export_tokens]
420pub struct FindOneAndReplaceOptions {
421    /// Opt out of document-level validation.
422    pub bypass_document_validation: Option<bool>,
423
424    /// The maximum amount of time to allow the query to run.
425    ///
426    /// This options maps to the `maxTimeMS` MongoDB query option, so the duration will be sent
427    /// across the wire as an integer number of milliseconds.
428    pub max_time: Option<Duration>,
429
430    /// Limits the fields of the document being returned.
431    pub projection: Option<Document>,
432
433    /// Whether the operation should return the document before or after modification.
434    pub return_document: Option<ReturnDocument>,
435
436    /// The order of the documents for the purposes of the operation.
437    pub sort: Option<Document>,
438
439    /// If true, insert a document if no matching document is found.
440    pub upsert: Option<bool>,
441
442    /// The level of the write concern
443    #[serde(skip_serializing_if = "write_concern_is_empty")]
444    pub write_concern: Option<WriteConcern>,
445
446    /// The collation to use for the operation.
447    ///
448    /// See the [documentation](https://www.mongodb.com/docs/manual/reference/collation/) for more
449    /// information on how to use this option.
450    pub collation: Option<Collation>,
451
452    /// The index to use for the operation.
453    /// Only available in MongoDB 4.4+.
454    pub hint: Option<Hint>,
455
456    /// Map of parameter names and values. Values must be constant or closed
457    /// expressions that do not reference document fields. Parameters can then be
458    /// accessed as variables in an aggregate expression context (e.g. "$$var").
459    ///
460    /// Only available in MongoDB 5.0+.
461    #[serde(rename = "let")]
462    pub let_vars: Option<Document>,
463
464    /// Tags the query with an arbitrary [`Bson`] value to help trace the operation through the
465    /// database profiler, currentOp and logs.
466    ///
467    /// This option is only available on server versions 4.4+.
468    pub comment: Option<Bson>,
469}
470
471/// Specifies the options to a
472/// [`Collection::find_one_and_update`](../struct.Collection.html#method.find_one_and_update)
473/// operation.
474#[skip_serializing_none]
475#[derive(Clone, Debug, Default, Deserialize, TypedBuilder)]
476#[serde(rename_all = "camelCase")]
477#[builder(field_defaults(default, setter(into)))]
478#[non_exhaustive]
479#[export_tokens]
480pub struct FindOneAndUpdateOptions {
481    /// A set of filters specifying to which array elements an update should apply.
482    ///
483    /// See the documentation [here](https://www.mongodb.com/docs/manual/reference/command/update/) for
484    /// more information on array filters.
485    pub array_filters: Option<Vec<Document>>,
486
487    /// Opt out of document-level validation.
488    pub bypass_document_validation: Option<bool>,
489
490    /// The maximum amount of time to allow the query to run.
491    ///
492    /// This options maps to the `maxTimeMS` MongoDB query option, so the duration will be sent
493    /// across the wire as an integer number of milliseconds.
494    pub max_time: Option<Duration>,
495
496    /// Limits the fields of the document being returned.
497    pub projection: Option<Document>,
498
499    /// Whether the operation should return the document before or after modification.
500    pub return_document: Option<ReturnDocument>,
501
502    /// The order of the documents for the purposes of the operation.
503    pub sort: Option<Document>,
504
505    /// If true, insert a document if no matching document is found.
506    pub upsert: Option<bool>,
507
508    /// The level of the write concern
509    #[serde(skip_serializing_if = "write_concern_is_empty")]
510    pub write_concern: Option<WriteConcern>,
511
512    /// The collation to use for the operation.
513    ///
514    /// See the [documentation](https://www.mongodb.com/docs/manual/reference/collation/) for more
515    /// information on how to use this option.
516    pub collation: Option<Collation>,
517
518    /// The index to use for the operation.
519    /// Only available in MongoDB 4.4+.
520    pub hint: Option<Hint>,
521
522    /// Map of parameter names and values. Values must be constant or closed
523    /// expressions that do not reference document fields. Parameters can then be
524    /// accessed as variables in an aggregate expression context (e.g. "$$var").
525    ///
526    /// Only available in MongoDB 5.0+.
527    #[serde(rename = "let")]
528    pub let_vars: Option<Document>,
529
530    /// Tags the query with an arbitrary [`Bson`] value to help trace the operation through the
531    /// database profiler, currentOp and logs.
532    ///
533    /// This option is only available on server versions 4.4+.
534    pub comment: Option<Bson>,
535}
536
537/// Specifies the options to a [`Collection::aggregate`](../struct.Collection.html#method.aggregate)
538/// operation.
539#[skip_serializing_none]
540#[derive(Clone, Debug, Default, Deserialize, TypedBuilder, Serialize)]
541#[serde(rename_all = "camelCase")]
542#[builder(field_defaults(default, setter(into)))]
543#[non_exhaustive]
544#[export_tokens]
545pub struct AggregateOptions {
546    /// Enables writing to temporary files. When set to true, aggregation stages can write data to
547    /// the _tmp subdirectory in the dbPath directory.
548    pub allow_disk_use: Option<bool>,
549
550    /// The number of documents the server should return per cursor batch.
551    ///
552    /// Note that this does not have any affect on the documents that are returned by a cursor,
553    /// only the number of documents kept in memory at a given time (and by extension, the
554    /// number of round trips needed to return the entire set of documents returned by the
555    /// query).
556    #[serde(
557        serialize_with = "serde_util::serialize_u32_option_as_batch_size",
558        rename(serialize = "cursor")
559    )]
560    pub batch_size: Option<u32>,
561
562    /// Opt out of document-level validation.
563    pub bypass_document_validation: Option<bool>,
564
565    /// The collation to use for the operation.
566    ///
567    /// See the [documentation](https://www.mongodb.com/docs/manual/reference/collation/) for more
568    /// information on how to use this option.
569    pub collation: Option<Collation>,
570
571    /// Tags the query with an arbitrary [`Bson`] value to help trace the operation through the
572    /// database profiler, currentOp and logs.
573    ///
574    /// For server versions less than 4.4, only a string value may be provided.
575    pub comment: Option<Bson>,
576
577    /// The index to use for the operation.
578    pub hint: Option<Hint>,
579
580    /// The maximum amount of time for the server to wait on new documents to satisfy a tailable
581    /// await cursor query.
582    ///
583    /// This option will have no effect on non-tailable cursors that result from this operation.
584    #[serde(
585        skip_serializing,
586        deserialize_with = "serde_util::deserialize_duration_option_from_u64_millis",
587        default
588    )]
589    pub max_await_time: Option<Duration>,
590
591    /// The maximum amount of time to allow the query to run.
592    ///
593    /// This options maps to the `maxTimeMS` MongoDB query option, so the duration will be sent
594    /// across the wire as an integer number of milliseconds.
595    #[serde(
596        serialize_with = "serde_util::serialize_duration_option_as_int_millis",
597        rename = "maxTimeMS",
598        deserialize_with = "serde_util::deserialize_duration_option_from_u64_millis",
599        default
600    )]
601    pub max_time: Option<Duration>,
602
603    /// The read concern to use for the operation.
604    ///
605    /// If none is specified, the read concern defined on the object executing this operation will
606    /// be used.
607    #[serde(skip_serializing)]
608    pub read_concern: Option<ReadConcern>,
609
610    /// The criteria used to select a server for this operation.
611    ///
612    /// If none is specified, the selection criteria defined on the object executing this operation
613    /// will be used.
614    #[serde(skip_serializing)]
615    #[serde(rename = "readPreference")]
616    pub selection_criteria: Option<SelectionCriteria>,
617
618    /// The write concern to use for the operation.
619    ///
620    /// If none is specified, the write concern defined on the object executing this operation will
621    /// be used.
622    #[serde(skip_serializing_if = "write_concern_is_empty")]
623    pub write_concern: Option<WriteConcern>,
624
625    /// A document with any amount of parameter names, each followed by definitions of constants in
626    /// the MQL Aggregate Expression language.  Each parameter name is then usable to access the
627    /// value of the corresponding MQL Expression with the "$$" syntax within Aggregate Expression
628    /// contexts.
629    ///
630    /// This feature is only available on server versions 5.0 and above.
631    #[serde(rename = "let")]
632    pub let_vars: Option<Document>,
633}
634
635/// Specifies the options to a
636/// [`Collection::count_documents`](../struct.Collection.html#method.count_documents) operation.
637#[skip_serializing_none]
638#[derive(Clone, Debug, Default, Deserialize, TypedBuilder)]
639#[serde(rename_all = "camelCase")]
640#[builder(field_defaults(default, setter(into)))]
641#[non_exhaustive]
642#[export_tokens]
643pub struct CountOptions {
644    /// The index to use for the operation.
645    pub hint: Option<Hint>,
646
647    /// The maximum number of documents to count.
648    pub limit: Option<u64>,
649
650    /// The maximum amount of time to allow the query to run.
651    ///
652    /// This options maps to the `maxTimeMS` MongoDB query option, so the duration will be sent
653    /// across the wire as an integer number of milliseconds.
654    #[serde(
655        default,
656        deserialize_with = "serde_util::deserialize_duration_option_from_u64_millis"
657    )]
658    pub max_time: Option<Duration>,
659
660    /// The number of documents to skip before counting.
661    pub skip: Option<u64>,
662
663    /// The collation to use for the operation.
664    ///
665    /// See the [documentation](https://www.mongodb.com/docs/manual/reference/collation/) for more
666    /// information on how to use this option.
667    pub collation: Option<Collation>,
668
669    /// The criteria used to select a server for this operation.
670    ///
671    /// If none specified, the default set on the collection will be used.
672    pub selection_criteria: Option<SelectionCriteria>,
673
674    /// The level of the read concern.
675    #[serde(skip_serializing)]
676    pub read_concern: Option<ReadConcern>,
677
678    /// Tags the query with an arbitrary [`Bson`] value to help trace the operation through the
679    /// database profiler, currentOp and logs.
680    ///
681    /// This option is only available on server versions 4.4+.
682    pub comment: Option<Bson>,
683}
684
685// rustfmt tries to split the link up when it's all on one line, which breaks the link, so we wrap
686// the link contents in whitespace to get it to render correctly.
687//
688/// Specifies the options to a
689/// [
690///  `Collection::estimated_document_count`
691/// ](../struct.Collection.html#method.estimated_document_count) operation.
692#[serde_with::skip_serializing_none]
693#[derive(Debug, Default, Deserialize, TypedBuilder, Serialize, Clone)]
694#[serde(rename_all = "camelCase")]
695#[builder(field_defaults(default, setter(into)))]
696#[non_exhaustive]
697#[export_tokens]
698pub struct EstimatedDocumentCountOptions {
699    /// The maximum amount of time to allow the query to run.
700    ///
701    /// This options maps to the `maxTimeMS` MongoDB query option, so the duration will be sent
702    /// across the wire as an integer number of milliseconds.
703    #[serde(
704        default,
705        serialize_with = "serde_util::serialize_duration_option_as_int_millis",
706        rename = "maxTimeMS",
707        deserialize_with = "serde_util::deserialize_duration_option_from_u64_millis"
708    )]
709    pub max_time: Option<Duration>,
710
711    /// The criteria used to select a server for this operation.
712    ///
713    /// If none specified, the default set on the collection will be used.
714    #[serde(skip_serializing)]
715    pub selection_criteria: Option<SelectionCriteria>,
716
717    /// The level of the read concern.
718    #[serde(skip_serializing)]
719    pub read_concern: Option<ReadConcern>,
720
721    /// Tags the query with an arbitrary [`Bson`] value to help trace the operation through the
722    /// database profiler, currentOp and logs.
723    ///
724    /// This option is only supported on server versions 4.4+. The comment can be any [`Bson`]
725    /// value on server versions 4.4.14+. On server versions between 4.4.0 and 4.4.14, only
726    /// [`Bson::String`] values are supported.
727    pub comment: Option<Bson>,
728}
729
730/// Specifies the options to a [`Collection::distinct`](../struct.Collection.html#method.distinct)
731/// operation.
732#[serde_with::skip_serializing_none]
733#[derive(Debug, Default, Deserialize, TypedBuilder, Serialize, Clone)]
734#[builder(field_defaults(default, setter(into)))]
735#[serde(rename_all = "camelCase")]
736#[non_exhaustive]
737#[export_tokens]
738pub struct DistinctOptions {
739    /// The maximum amount of time to allow the query to run.
740    ///
741    /// This options maps to the `maxTimeMS` MongoDB query option, so the duration will be sent
742    /// across the wire as an integer number of milliseconds.
743    #[serde(
744        default,
745        serialize_with = "serde_util::serialize_duration_option_as_int_millis",
746        rename = "maxTimeMS",
747        deserialize_with = "serde_util::deserialize_duration_option_from_u64_millis"
748    )]
749    pub max_time: Option<Duration>,
750
751    /// The criteria used to select a server for this operation.
752    ///
753    /// If none specified, the default set on the collection will be used.
754    #[serde(skip_serializing)]
755    pub selection_criteria: Option<SelectionCriteria>,
756
757    /// The level of the read concern.
758    #[serde(skip_serializing)]
759    pub read_concern: Option<ReadConcern>,
760
761    /// The collation to use for the operation.
762    ///
763    /// See the [documentation](https://www.mongodb.com/docs/manual/reference/collation/) for more
764    /// information on how to use this option.
765    pub collation: Option<Collation>,
766
767    /// Tags the query with an arbitrary [`Bson`] value to help trace the operation through the
768    /// database profiler, currentOp and logs.
769    ///
770    /// This option is only available on server versions 4.4+.
771    pub comment: Option<Bson>,
772
773    /// A document or string that specifies the index to use to support the query predicate.
774    /// Available on server versions 7.1+.
775    pub hint: Option<Hint>,
776}
777
778/// Specifies the options to a [`Collection::find`](../struct.Collection.html#method.find)
779/// operation.
780#[skip_serializing_none]
781#[derive(Clone, Debug, Default, Deserialize, TypedBuilder, Serialize)]
782#[builder(field_defaults(default, setter(into)))]
783#[serde(rename_all = "camelCase")]
784#[non_exhaustive]
785#[export_tokens]
786pub struct FindOptions {
787    /// Enables writing to temporary files by the server. When set to true, the find operation can
788    /// write data to the _tmp subdirectory in the dbPath directory. Only supported in server
789    /// versions 4.4+.
790    pub allow_disk_use: Option<bool>,
791
792    /// If true, partial results will be returned from a mongos rather than an error being
793    /// returned if one or more shards is down.
794    pub allow_partial_results: Option<bool>,
795
796    /// The number of documents the server should return per cursor batch.
797    ///
798    /// Note that this does not have any affect on the documents that are returned by a cursor,
799    /// only the number of documents kept in memory at a given time (and by extension, the
800    /// number of round trips needed to return the entire set of documents returned by the
801    /// query.
802    #[serde(serialize_with = "serde_util::serialize_u32_option_as_i32")]
803    pub batch_size: Option<u32>,
804
805    /// Tags the query with an arbitrary [`Bson`] value to help trace the operation through the
806    /// database profiler, currentOp and logs.
807    ///
808    /// For server versions less than 4.4, only a string value may be provided.
809    pub comment: Option<Bson>,
810
811    /// The type of cursor to return.
812    #[serde(skip)]
813    pub cursor_type: Option<CursorType>,
814
815    /// The index to use for the operation.
816    pub hint: Option<Hint>,
817
818    /// The maximum number of documents to query.
819    /// If a negative number is specified, the documents will be returned in a single batch limited
820    /// in number by the positive value of the specified limit.
821    #[serde(serialize_with = "serialize_absolute_value")]
822    pub limit: Option<i64>,
823
824    /// The exclusive upper bound for a specific index.
825    pub max: Option<Document>,
826
827    /// The maximum amount of time for the server to wait on new documents to satisfy a tailable
828    /// cursor query. If the cursor is not tailable, this option is ignored.
829    #[serde(skip)]
830    pub max_await_time: Option<Duration>,
831
832    /// Maximum number of documents or index keys to scan when executing the query.
833    ///
834    /// Note: this option is deprecated starting in MongoDB version 4.0 and removed in MongoDB 4.2.
835    /// Use the maxTimeMS option instead.
836    #[serde(serialize_with = "serde_util::serialize_u64_option_as_i64")]
837    pub max_scan: Option<u64>,
838
839    /// The maximum amount of time to allow the query to run.
840    ///
841    /// This options maps to the `maxTimeMS` MongoDB query option, so the duration will be sent
842    /// across the wire as an integer number of milliseconds.
843    #[serde(
844        rename = "maxTimeMS",
845        serialize_with = "serde_util::serialize_duration_option_as_int_millis"
846    )]
847    pub max_time: Option<Duration>,
848
849    /// The inclusive lower bound for a specific index.
850    pub min: Option<Document>,
851
852    /// Whether the server should close the cursor after a period of inactivity.
853    pub no_cursor_timeout: Option<bool>,
854
855    /// The [projection document](https://www.mongodb.com/docs/manual/reference/method/db.collection.find/#projection)
856    /// to determine which fields to include in the returned document.
857    ///
858    /// Specifying this option may cause deserialization errors if the returned fields do not fit
859    /// the schema of the collection's generic type. The
860    /// [`clone_with_type`](crate::Collection::clone_with_type) method can be used to retrieve a
861    /// handle to the collection with a different generic type configured.
862    pub projection: Option<Document>,
863
864    /// The read concern to use for this find query.
865    ///
866    /// If none specified, the default set on the collection will be used.
867    #[serde(skip_serializing)]
868    pub read_concern: Option<ReadConcern>,
869
870    /// Whether to return only the index keys in the documents.
871    pub return_key: Option<bool>,
872
873    /// The criteria used to select a server for this find query.
874    ///
875    /// If none specified, the default set on the collection will be used.
876    #[serde(skip)]
877    pub selection_criteria: Option<SelectionCriteria>,
878
879    /// Whether to return the record identifier for each document. If true, adds a `$recordId`
880    /// field to the returned documents.
881    ///
882    /// Defaults to false.
883    pub show_record_id: Option<bool>,
884
885    /// The number of documents to skip before counting.
886    #[serde(serialize_with = "serde_util::serialize_u64_option_as_i64")]
887    pub skip: Option<u64>,
888
889    /// The order of the documents for the purposes of the operation.
890    pub sort: Option<Document>,
891
892    /// The collation to use for the operation.
893    ///
894    /// See the [documentation](https://www.mongodb.com/docs/manual/reference/collation/) for more
895    /// information on how to use this option.
896    pub collation: Option<Collation>,
897
898    /// Map of parameter names and values. Values must be constant or closed
899    /// expressions that do not reference document fields. Parameters can then be
900    /// accessed as variables in an aggregate expression context (e.g. "$$var").
901    ///
902    /// Only available in MongoDB 5.0+.
903    #[serde(rename = "let")]
904    pub let_vars: Option<Document>,
905}
906
907impl From<FindOneOptions> for FindOptions {
908    fn from(options: FindOneOptions) -> Self {
909        FindOptions {
910            allow_disk_use: None,
911            allow_partial_results: options.allow_partial_results,
912            collation: options.collation,
913            comment: options.comment,
914            hint: options.hint,
915            max: options.max,
916            max_scan: options.max_scan,
917            max_time: options.max_time,
918            min: options.min,
919            projection: options.projection,
920            read_concern: options.read_concern,
921            return_key: options.return_key,
922            selection_criteria: options.selection_criteria,
923            show_record_id: options.show_record_id,
924            skip: options.skip,
925            batch_size: None,
926            cursor_type: None,
927            limit: Some(-1),
928            max_await_time: None,
929            no_cursor_timeout: None,
930            sort: options.sort,
931            let_vars: options.let_vars,
932        }
933    }
934}
935
936/// Custom serializer used to serialize limit as its absolute value.
937fn serialize_absolute_value<S>(
938    val: &Option<i64>,
939    serializer: S,
940) -> std::result::Result<S::Ok, S::Error>
941where
942    S: Serializer,
943{
944    match val {
945        Some(v) => serializer.serialize_i64(v.abs()),
946        None => serializer.serialize_none(),
947    }
948}
949
950/// Specifies the options to a [`Collection::find_one`](../struct.Collection.html#method.find_one)
951/// operation.
952#[derive(Clone, Debug, Default, Deserialize, TypedBuilder)]
953#[serde(rename_all = "camelCase")]
954#[builder(field_defaults(default, setter(into)))]
955#[non_exhaustive]
956#[export_tokens]
957pub struct FindOneOptions {
958    /// If true, partial results will be returned from a mongos rather than an error being
959    /// returned if one or more shards is down.
960    pub allow_partial_results: Option<bool>,
961
962    /// The collation to use for the operation.
963    ///
964    /// See the [documentation](https://www.mongodb.com/docs/manual/reference/collation/) for more
965    /// information on how to use this option.
966    pub collation: Option<Collation>,
967
968    /// Tags the query with an arbitrary [`Bson`] value to help trace the operation through the
969    /// database profiler, currentOp and logs.
970    ///
971    /// For server versions less than 4.4, only a string value may be provided.
972    pub comment: Option<Bson>,
973
974    /// The index to use for the operation.
975    pub hint: Option<Hint>,
976
977    /// The exclusive upper bound for a specific index.
978    pub max: Option<Document>,
979
980    /// Maximum number of documents or index keys to scan when executing the query.
981    ///
982    /// Note: this option is deprecated starting in MongoDB version 4.0 and removed in MongoDB 4.2.
983    /// Use the maxTimeMS option instead.
984    #[serde(serialize_with = "bson_util::serialize_u64_option_as_i64")]
985    pub max_scan: Option<u64>,
986
987    /// The maximum amount of time to allow the query to run.
988    ///
989    /// This options maps to the `maxTimeMS` MongoDB query option, so the duration will be sent
990    /// across the wire as an integer number of milliseconds.
991    #[serde(
992        default,
993        deserialize_with = "serde_util::deserialize_duration_option_from_u64_millis"
994    )]
995    pub max_time: Option<Duration>,
996
997    /// The inclusive lower bound for a specific index.
998    pub min: Option<Document>,
999
1000    /// Limits the fields of the document being returned.
1001    pub projection: Option<Document>,
1002
1003    /// The read concern to use for this find query.
1004    ///
1005    /// If none specified, the default set on the collection will be used.
1006    #[serde(skip_serializing)]
1007    pub read_concern: Option<ReadConcern>,
1008
1009    /// Whether to return only the index keys in the documents.
1010    pub return_key: Option<bool>,
1011
1012    /// The criteria used to select a server for this find query.
1013    ///
1014    /// If none specified, the default set on the collection will be used.
1015    pub selection_criteria: Option<SelectionCriteria>,
1016
1017    /// Whether to return the record identifier for each document.
1018    pub show_record_id: Option<bool>,
1019
1020    /// The number of documents to skip before counting.
1021    #[serde(serialize_with = "bson_util::serialize_u64_option_as_i64")]
1022    pub skip: Option<u64>,
1023
1024    /// The order of the documents for the purposes of the operation.
1025    pub sort: Option<Document>,
1026
1027    /// Map of parameter names and values. Values must be constant or closed
1028    /// expressions that do not reference document fields. Parameters can then be
1029    /// accessed as variables in an aggregate expression context (e.g. "$$var").
1030    ///
1031    /// Only available in MongoDB 5.0+.
1032    #[serde(rename = "let")]
1033    pub let_vars: Option<Document>,
1034}
1035
1036/// Specifies the options to a
1037/// [`Collection::create_index`](../struct.Collection.html#method.create_index) or [`Collection::
1038/// create_indexes`](../struct.Collection.html#method.create_indexes) operation.
1039///
1040/// For more information, see [`createIndexes`](https://www.mongodb.com/docs/manual/reference/command/createIndexes/).
1041#[serde_with::skip_serializing_none]
1042#[derive(Clone, Debug, Default, TypedBuilder, Serialize)]
1043#[builder(field_defaults(default, setter(into)))]
1044#[serde(rename_all = "camelCase", deny_unknown_fields)]
1045#[non_exhaustive]
1046#[export_tokens]
1047pub struct CreateIndexOptions {
1048    /// Specify the commit quorum needed to mark an `index` as ready.
1049    pub commit_quorum: Option<CommitQuorum>,
1050
1051    /// The maximum amount of time to allow the index to build.
1052    ///
1053    /// This option maps to the `maxTimeMS` MongoDB query option, so the duration will be sent
1054    /// across the wire as an integer number of milliseconds.
1055    #[serde(
1056        rename = "maxTimeMS",
1057        default,
1058        serialize_with = "serde_util::serialize_duration_option_as_int_millis",
1059        deserialize_with = "serde_util::deserialize_duration_option_from_u64_millis"
1060    )]
1061    pub max_time: Option<Duration>,
1062
1063    /// The write concern for the operation.
1064    #[serde(skip_serializing_if = "write_concern_is_empty")]
1065    pub write_concern: Option<WriteConcern>,
1066
1067    /// Tags the query with an arbitrary [`Bson`] value to help trace the operation through the
1068    /// database profiler, currentOp and logs.
1069    ///
1070    /// This option is only available on server versions 4.4+.
1071    pub comment: Option<Bson>,
1072}
1073
1074/// Specifies the options to a [`Collection::drop`](../struct.Collection.html#method.drop)
1075/// operation.
1076#[serde_with::skip_serializing_none]
1077#[derive(Clone, Debug, Default, Deserialize, TypedBuilder, Serialize)]
1078#[serde(rename_all = "camelCase")]
1079#[builder(field_defaults(default, setter(into)))]
1080#[non_exhaustive]
1081#[export_tokens]
1082pub struct DropCollectionOptions {
1083    /// The write concern for the operation.
1084    #[serde(skip_serializing_if = "write_concern_is_empty")]
1085    pub write_concern: Option<WriteConcern>,
1086
1087    /// Map of encrypted fields for the collection.
1088    // Serialization is skipped because the server doesn't accept this option; it's needed for
1089    // preprocessing.  Deserialization needs to remain because it's used in test files.
1090    #[cfg(feature = "in-use-encryption")]
1091    #[serde(skip_serializing)]
1092    pub encrypted_fields: Option<Document>,
1093}
1094
1095/// Specifies the options to a
1096/// [`Collection::drop_index`](../struct.Collection.html#method.drop_index) or
1097/// [`Collection::drop_indexes`](../struct.Collection.html#method.drop_indexes) operation.
1098#[serde_with::skip_serializing_none]
1099#[derive(Clone, Debug, Default, Deserialize, TypedBuilder, Serialize)]
1100#[serde(rename_all = "camelCase", deny_unknown_fields)]
1101#[builder(field_defaults(default, setter(into)))]
1102#[non_exhaustive]
1103#[export_tokens]
1104pub struct DropIndexOptions {
1105    /// The maximum amount of time to allow the index to drop.
1106    ///
1107    /// This option maps to the `maxTimeMS` MongoDB query option, so the duration will be sent
1108    /// across the wire as an integer number of milliseconds.
1109    #[serde(
1110        rename = "maxTimeMS",
1111        default,
1112        serialize_with = "serde_util::serialize_duration_option_as_int_millis",
1113        deserialize_with = "serde_util::deserialize_duration_option_from_u64_millis"
1114    )]
1115    pub max_time: Option<Duration>,
1116
1117    /// The write concern for the operation.
1118    #[serde(skip_serializing_if = "write_concern_is_empty")]
1119    pub write_concern: Option<WriteConcern>,
1120
1121    /// Tags the query with an arbitrary [`Bson`] value to help trace the operation through the
1122    /// database profiler, currentOp and logs.
1123    ///
1124    /// This option is only available on server versions 4.4+.
1125    pub comment: Option<Bson>,
1126}
1127
1128/// Specifies the options to a
1129/// [`Collection::list_indexes`](../struct.Collection.html#method.list_indexes) operation.
1130#[serde_with::skip_serializing_none]
1131#[derive(Clone, Debug, Default, Deserialize, TypedBuilder, Serialize)]
1132#[serde(rename_all = "camelCase", deny_unknown_fields)]
1133#[builder(field_defaults(default, setter(into)))]
1134#[non_exhaustive]
1135#[export_tokens]
1136pub struct ListIndexesOptions {
1137    /// The maximum amount of time to search for the index.
1138    ///
1139    /// This option maps to the `maxTimeMS` MongoDB query option, so the duration will be sent
1140    /// across the wire as an integer number of milliseconds.
1141    #[serde(
1142        rename = "maxTimeMS",
1143        default,
1144        serialize_with = "serde_util::serialize_duration_option_as_int_millis",
1145        deserialize_with = "serde_util::deserialize_duration_option_from_u64_millis"
1146    )]
1147    pub max_time: Option<Duration>,
1148
1149    /// The number of indexes the server should return per cursor batch.
1150    #[serde(default, skip_serializing)]
1151    pub batch_size: Option<u32>,
1152
1153    /// Tags the query with an arbitrary [`Bson`] value to help trace the operation through the
1154    /// database profiler, currentOp and logs.
1155    ///
1156    /// This option is only available on server versions 4.4+.
1157    pub comment: Option<Bson>,
1158}
1159
1160/// The minimum number of data-bearing voting replica set members (i.e. commit quorum), including
1161/// the primary, that must report a successful index build before the primary marks the indexes as
1162/// ready.
1163///
1164/// For more information, see the [documentation](https://www.mongodb.com/docs/manual/reference/command/createIndexes/#definition)
1165#[derive(Clone, Debug, PartialEq)]
1166#[non_exhaustive]
1167pub enum CommitQuorum {
1168    /// A specific number of voting replica set members. When set to 0, disables quorum voting.
1169    Nodes(u32),
1170
1171    /// All data-bearing voting replica set members (default).
1172    VotingMembers,
1173
1174    /// A simple majority of voting members.
1175    Majority,
1176
1177    /// A replica set tag name.
1178    Custom(String),
1179}
1180
1181impl Serialize for CommitQuorum {
1182    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
1183    where
1184        S: Serializer,
1185    {
1186        match self {
1187            CommitQuorum::Nodes(n) => serde_util::serialize_u32_as_i32(n, serializer),
1188            CommitQuorum::VotingMembers => serializer.serialize_str("votingMembers"),
1189            CommitQuorum::Majority => serializer.serialize_str("majority"),
1190            CommitQuorum::Custom(s) => serializer.serialize_str(s),
1191        }
1192    }
1193}
1194
1195impl<'de> Deserialize<'de> for CommitQuorum {
1196    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
1197    where
1198        D: Deserializer<'de>,
1199    {
1200        #[derive(Deserialize)]
1201        #[serde(untagged)]
1202        enum IntOrString {
1203            Int(u32),
1204            String(String),
1205        }
1206        match IntOrString::deserialize(deserializer)? {
1207            IntOrString::String(s) => {
1208                if s == "votingMembers" {
1209                    Ok(CommitQuorum::VotingMembers)
1210                } else if s == "majority" {
1211                    Ok(CommitQuorum::Majority)
1212                } else {
1213                    Ok(CommitQuorum::Custom(s))
1214                }
1215            }
1216            IntOrString::Int(i) => Ok(CommitQuorum::Nodes(i)),
1217        }
1218    }
1219}