mongodb/db/options.rs
1use std::time::Duration;
2
3use crate::bson::doc;
4use macro_magic::export_tokens;
5use serde::{Deserialize, Serialize};
6use serde_with::skip_serializing_none;
7use typed_builder::TypedBuilder;
8
9use crate::{
10 bson::{Bson, Document},
11 concern::{ReadConcern, WriteConcern},
12 options::{Collation, CursorType},
13 selection_criteria::SelectionCriteria,
14 serde_util,
15};
16
17/// These are the valid options for creating a [`Database`](../struct.Database.html) with
18/// [`Client::database_with_options`](../struct.Client.html#method.database_with_options).
19#[derive(Clone, Debug, Default, Deserialize, TypedBuilder)]
20#[builder(field_defaults(default, setter(into)))]
21#[non_exhaustive]
22pub struct DatabaseOptions {
23 /// The default read preference for operations.
24 pub selection_criteria: Option<SelectionCriteria>,
25
26 /// The default read concern for operations.
27 pub read_concern: Option<ReadConcern>,
28
29 /// The default write concern for operations.
30 pub write_concern: Option<WriteConcern>,
31}
32
33/// These are the valid options for creating a collection with
34/// [`Database::create_collection`](../struct.Database.html#method.create_collection).
35#[skip_serializing_none]
36#[derive(Clone, Debug, Default, Deserialize, TypedBuilder, Serialize)]
37#[serde(rename_all = "camelCase")]
38#[builder(field_defaults(default, setter(into)))]
39#[non_exhaustive]
40#[export_tokens]
41pub struct CreateCollectionOptions {
42 /// Whether the collection should be capped. If true, `size` must also be set.
43 pub capped: Option<bool>,
44
45 /// The maximum size (in bytes) for a capped collection. This option is ignored if `capped` is
46 /// not set to true.
47 #[serde(
48 serialize_with = "serde_util::serialize_u64_option_as_i64",
49 deserialize_with = "serde_util::deserialize_option_u64_from_bson_number",
50 default
51 )]
52 pub size: Option<u64>,
53
54 /// The maximum number of documents in a capped collection. The `size` limit takes precedence
55 /// over this option. If a capped collection reaches the size limit before it reaches the
56 /// maximum number of documents, MongoDB removes old documents.
57 #[serde(serialize_with = "serde_util::serialize_u64_option_as_i64")]
58 pub max: Option<u64>,
59
60 /// The storage engine that the collection should use. The value should take the following
61 /// form:
62 ///
63 /// `{ <storage-engine-name>: <options> }`
64 pub storage_engine: Option<Document>,
65
66 /// Specifies a validator to restrict the schema of documents which can exist in the
67 /// collection. Expressions can be specified using any query operators except `$near`,
68 /// `$nearSphere`, `$text`, and `$where`.
69 pub validator: Option<Document>,
70
71 /// Specifies how strictly the database should apply the validation rules to existing documents
72 /// during an update.
73 pub validation_level: Option<ValidationLevel>,
74
75 /// Specifies whether the database should return an error or simply raise a warning if inserted
76 /// documents do not pass the validation.
77 pub validation_action: Option<ValidationAction>,
78
79 /// The name of the source collection or view to base this view on. If specified, this will
80 /// cause a view to be created rather than a collection.
81 pub view_on: Option<String>,
82
83 /// An array that consists of the aggregation pipeline stages to run against `view_on` to
84 /// determine the contents of the view.
85 pub pipeline: Option<Vec<Document>>,
86
87 /// The default collation for the collection or view.
88 pub collation: Option<Collation>,
89
90 /// The write concern for the operation.
91 #[serde(skip_serializing)]
92 pub write_concern: Option<WriteConcern>,
93
94 /// The default configuration for indexes created on this collection, including the _id index.
95 pub index_option_defaults: Option<IndexOptionDefaults>,
96
97 /// An object containing options for creating time series collections. See the [`create`
98 /// command documentation](https://www.mongodb.com/docs/manual/reference/command/create/) for
99 /// supported options, and the [Time Series Collections documentation](
100 /// https://www.mongodb.com/docs/manual/core/timeseries-collections/) for more information.
101 ///
102 /// This feature is only available on server versions 5.0 and above.
103 pub timeseries: Option<TimeseriesOptions>,
104
105 /// Used to automatically delete documents in time series collections. See the [`create`
106 /// command documentation](https://www.mongodb.com/docs/manual/reference/command/create/) for more
107 /// information.
108 #[serde(default, with = "serde_util::duration_option_as_int_seconds")]
109 pub expire_after_seconds: Option<Duration>,
110
111 /// Options for supporting change stream pre- and post-images.
112 pub change_stream_pre_and_post_images: Option<ChangeStreamPreAndPostImages>,
113
114 /// Options for clustered collections. This option is only available on server versions 5.3+.
115 #[serde(default, deserialize_with = "ClusteredIndex::deserialize_self_or_true")]
116 pub clustered_index: Option<ClusteredIndex>,
117
118 /// Tags the query with an arbitrary [`Bson`] value to help trace the operation through the
119 /// database profiler, currentOp and logs.
120 ///
121 /// This option is only available on server versions 4.4+.
122 pub comment: Option<Bson>,
123
124 /// Map of encrypted fields for the created collection.
125 #[cfg(feature = "in-use-encryption")]
126 pub encrypted_fields: Option<Document>,
127}
128
129/// Specifies how strictly the database should apply validation rules to existing documents during
130/// an update.
131#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
132#[serde(rename_all = "camelCase")]
133#[non_exhaustive]
134pub enum ValidationLevel {
135 /// Perform no validation for inserts and updates.
136 Off,
137 /// Perform validation on all inserts and updates.
138 Strict,
139 /// Perform validation on inserts as well as updates on existing valid documents, but do not
140 /// perform validations on updates on existing invalid documents.
141 Moderate,
142}
143
144/// Specifies whether the database should return an error or simply raise a warning if inserted
145/// documents do not pass the validation.
146#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
147#[serde(rename_all = "camelCase")]
148#[non_exhaustive]
149pub enum ValidationAction {
150 /// Return an error if inserted documents do not pass the validation.
151 Error,
152 /// Raise a warning if inserted documents do not pass the validation.
153 Warn,
154}
155
156/// Specifies options for a clustered collection. Some fields have required values; the `Default`
157/// impl uses those values.
158#[skip_serializing_none]
159#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
160#[serde(rename_all = "camelCase")]
161#[non_exhaustive]
162pub struct ClusteredIndex {
163 /// Key pattern; currently required to be `{_id: 1}`.
164 pub key: Document,
165
166 /// Currently required to be `true`.
167 pub unique: bool,
168
169 /// Optional; will be automatically generated if not provided.
170 pub name: Option<String>,
171
172 /// Optional; currently must be `2` if provided.
173 pub v: Option<i32>,
174}
175
176impl Default for ClusteredIndex {
177 fn default() -> Self {
178 Self {
179 key: doc! { "_id": 1 },
180 unique: true,
181 name: None,
182 v: None,
183 }
184 }
185}
186
187impl ClusteredIndex {
188 /// When creating a time-series collection on MongoDB Atlas the `clusteredIndex` field of the
189 /// collection options is given as `true` instead of as an object that deserializes to
190 /// `ClusteredIndex`. This custom deserializer handles that case by using the default value for
191 /// `ClusteredIndex`.
192 fn deserialize_self_or_true<'de, D>(deserializer: D) -> Result<Option<ClusteredIndex>, D::Error>
193 where
194 D: serde::Deserializer<'de>,
195 {
196 #[derive(Debug, Deserialize)]
197 #[serde(untagged)]
198 enum ValueUnion {
199 Bool(bool),
200 ClusteredIndex(ClusteredIndex),
201 }
202
203 let value_option: Option<ValueUnion> = Deserialize::deserialize(deserializer)?;
204 value_option
205 .map(|value| match value {
206 ValueUnion::Bool(true) => Ok(ClusteredIndex::default()),
207 ValueUnion::Bool(false) => Err(serde::de::Error::custom(
208 "if clusteredIndex is a boolean it must be `true`",
209 )),
210 ValueUnion::ClusteredIndex(value) => Ok(value),
211 })
212 .transpose()
213 }
214}
215
216/// Specifies default configuration for indexes created on a collection, including the _id index.
217#[derive(Clone, Debug, TypedBuilder, PartialEq, Serialize, Deserialize)]
218#[builder(field_defaults(default, setter(into)))]
219#[serde(rename_all = "camelCase")]
220#[non_exhaustive]
221pub struct IndexOptionDefaults {
222 /// The `storageEngine` document should be in the following form:
223 ///
224 /// `{ <storage-engine-name>: <options> }`
225 pub storage_engine: Document,
226}
227
228/// Specifies options for creating a timeseries collection.
229#[skip_serializing_none]
230#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, TypedBuilder)]
231#[serde(rename_all = "camelCase")]
232#[builder(field_defaults(default, setter(into)))]
233#[non_exhaustive]
234pub struct TimeseriesOptions {
235 /// Name of the top-level field to be used for time. Inserted documents must have this field,
236 /// and the field must be of the BSON UTC datetime type.
237 pub time_field: String,
238
239 /// Name of the top-level field describing the series. This field is used to group related data
240 /// and may be of any BSON type, except for array. This name may not be the same as the
241 /// timeField or _id.
242 pub meta_field: Option<String>,
243
244 /// The units you'd use to describe the expected interval between subsequent measurements for a
245 /// time-series. Defaults to `TimeseriesGranularity::Seconds` if unset.
246 pub granularity: Option<TimeseriesGranularity>,
247
248 /// The maximum time between timestamps in the same bucket. This value must be between 1 and
249 /// 31,536,000 seconds. If this value is set, the same value should be set for
250 /// `bucket_rounding` and `granularity` should not be set.
251 ///
252 /// This option is only available on MongoDB 6.3+.
253 #[serde(
254 default,
255 with = "serde_util::duration_option_as_int_seconds",
256 rename = "bucketMaxSpanSeconds"
257 )]
258 pub bucket_max_span: Option<Duration>,
259
260 /// The time interval that determines the starting timestamp for a new bucket. When a document
261 /// requires a new bucket, MongoDB rounds down the document's timestamp value by this interval
262 /// to set the minimum time for the bucket. If this value is set, the same value should be set
263 /// for `bucket_max_span` and `granularity` should not be set.
264 ///
265 /// This option is only available on MongoDB 6.3+.
266 #[serde(
267 default,
268 with = "serde_util::duration_option_as_int_seconds",
269 rename = "bucketRoundingSeconds"
270 )]
271 pub bucket_rounding: Option<Duration>,
272}
273
274/// The units you'd use to describe the expected interval between subsequent measurements for a
275/// time-series.
276#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
277#[serde(rename_all = "camelCase")]
278#[non_exhaustive]
279pub enum TimeseriesGranularity {
280 /// The expected interval between subsequent measurements is in seconds.
281 Seconds,
282 /// The expected interval between subsequent measurements is in minutes.
283 Minutes,
284 /// The expected interval between subsequent measurements is in hours.
285 Hours,
286}
287
288/// Specifies the options to a [`Database::drop`](crate::Database::drop) operation.
289#[derive(Clone, Debug, Default, TypedBuilder, Serialize)]
290#[serde(rename_all = "camelCase")]
291#[builder(field_defaults(default, setter(into)))]
292#[non_exhaustive]
293#[export_tokens]
294pub struct DropDatabaseOptions {
295 /// The write concern for the operation.
296 #[serde(skip_serializing)]
297 pub write_concern: Option<WriteConcern>,
298}
299
300/// Specifies the options to a
301/// [`Database::list_collections`](../struct.Database.html#method.list_collections) operation.
302#[skip_serializing_none]
303#[derive(Clone, Debug, Default, Deserialize, TypedBuilder, Serialize)]
304#[serde(rename_all = "camelCase")]
305#[builder(field_defaults(default, setter(into)))]
306#[non_exhaustive]
307#[export_tokens]
308pub struct ListCollectionsOptions {
309 /// The number of documents the server should return per cursor batch.
310 ///
311 /// Note that this does not have any affect on the documents that are returned by a cursor,
312 /// only the number of documents kept in memory at a given time (and by extension, the
313 /// number of round trips needed to return the entire set of documents returned by the
314 /// query).
315 #[serde(
316 serialize_with = "serde_util::serialize_u32_option_as_batch_size",
317 rename(serialize = "cursor")
318 )]
319 pub batch_size: Option<u32>,
320
321 /// Tags the query with an arbitrary [`Bson`] value to help trace the operation through the
322 /// database profiler, currentOp and logs.
323 ///
324 /// This option is only available on server versions 4.4+.
325 pub comment: Option<Bson>,
326
327 /// Filters the list operation.
328 pub filter: Option<Document>,
329
330 /// When `true` and used with
331 /// [`list_collection_names`](crate::Database::list_collection_names), the command returns
332 /// only those collections for which the user has privileges. When used with
333 /// [`list_collections`](crate::Database::list_collections) this option has no effect.
334 pub authorized_collections: Option<bool>,
335}
336
337/// Specifies the options to a [`Client::list_databases`](crate::Client::list_databases) operation.
338#[skip_serializing_none]
339#[derive(Clone, Debug, Default, Deserialize, TypedBuilder, Serialize)]
340#[serde(rename_all = "camelCase")]
341#[builder(field_defaults(default, setter(into)))]
342#[non_exhaustive]
343#[export_tokens]
344pub struct ListDatabasesOptions {
345 /// Determines which databases to return based on the user's access privileges. This option is
346 /// only supported on server versions 4.0.5+.
347 pub authorized_databases: Option<bool>,
348
349 /// Tags the query with an arbitrary [`Bson`] value to help trace the operation through the
350 /// database profiler, currentOp and logs.
351 ///
352 /// This option is only available on server versions 4.4+.
353 pub comment: Option<Bson>,
354
355 /// Filters the query.
356 pub filter: Option<Document>,
357}
358
359/// Specifies how change stream pre- and post-images should be supported.
360#[derive(Clone, Debug, Default, Deserialize, TypedBuilder, Serialize)]
361#[serde(rename_all = "camelCase")]
362#[builder(field_defaults(default, setter(into)))]
363#[non_exhaustive]
364pub struct ChangeStreamPreAndPostImages {
365 /// If `true`, change streams will be able to include pre- and post-images.
366 pub enabled: bool,
367}
368
369/// Specifies the options to a
370/// [`Database::run_command`](crate::Database::run_command) operation.
371#[derive(Clone, Debug, Default, TypedBuilder)]
372#[builder(field_defaults(default, setter(into)))]
373#[non_exhaustive]
374#[export_tokens]
375pub struct RunCommandOptions {
376 /// The default read preference for operations.
377 pub selection_criteria: Option<SelectionCriteria>,
378}
379
380/// Specifies the options to a
381/// [`Database::run_cursor_command`](crate::Database::run_cursor_command) operation.
382#[derive(Clone, Debug, Default, Deserialize, TypedBuilder)]
383#[builder(field_defaults(default, setter(into)))]
384#[serde(rename_all = "camelCase")]
385#[serde(default)]
386#[non_exhaustive]
387#[export_tokens]
388pub struct RunCursorCommandOptions {
389 /// The default read preference for operations.
390 pub selection_criteria: Option<SelectionCriteria>,
391 /// The type of cursor to return.
392 pub cursor_type: Option<CursorType>,
393 /// Number of documents to return per batch.
394 pub batch_size: Option<u32>,
395 #[serde(rename = "maxtime", alias = "maxTimeMS")]
396 #[serde(deserialize_with = "serde_util::deserialize_duration_option_from_u64_millis")]
397 /// Optional non-negative integer value. Use this value to configure the maxTimeMS option sent
398 /// on subsequent getMore commands.
399 pub max_time: Option<Duration>,
400 /// Optional BSON value. Use this value to configure the comment option sent on subsequent
401 /// getMore commands.
402 pub comment: Option<Bson>,
403}