mongodb 3.6.0

The official MongoDB driver for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
use std::borrow::Borrow;

use macro_magic::export_tokens;
use serde::{Deserialize, Serialize};
use serde_with::skip_serializing_none;
use typed_builder::TypedBuilder;

use crate::{
    bson::{rawdoc, Array, Bson, Document, RawDocumentBuf},
    bson_compat::{cstr, serialize_to_raw_document_buf},
    bson_util::{
        extend_raw_document_buf,
        get_or_prepend_id_field,
        replacement_document_check,
        update_document_check,
    },
    error::{Error, Result},
    options::{UpdateModifications, WriteConcern},
    serde_util::serialize_bool_or_true,
    Collection,
    Namespace,
};

/// The supported options for [`bulk_write`](crate::Client::bulk_write).
#[skip_serializing_none]
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
#[export_tokens]
pub struct BulkWriteOptions {
    /// Whether the operations should be performed in the order in which they were specified. If
    /// true, no more writes will be performed if a single write fails. If false, writes will
    /// continue to be attempted if a single write fails.
    ///
    /// Defaults to true.
    #[serialize_always]
    #[serde(serialize_with = "serialize_bool_or_true")]
    pub ordered: Option<bool>,

    /// Whether document-level validation should be bypassed.
    ///
    /// Defaults to false.
    pub bypass_document_validation: Option<bool>,

    /// An arbitrary comment to help trace the operation through the database profiler, currentOp
    /// and logs.
    pub comment: Option<Bson>,

    /// A map of parameter names and values to apply to all operations within the bulk write.
    /// 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").
    #[serde(rename = "let")]
    pub let_vars: Option<Document>,

    /// The write concern to use for this operation.
    #[serde(skip_serializing)]
    pub write_concern: Option<WriteConcern>,
}

/// A single write to be performed within a [`bulk_write`](crate::Client::bulk_write) operation.
#[skip_serializing_none]
#[derive(Clone, Debug, Serialize)]
#[serde(untagged)]
#[non_exhaustive]
#[allow(missing_docs)]
pub enum WriteModel {
    InsertOne(InsertOneModel),
    UpdateOne(UpdateOneModel),
    UpdateMany(UpdateManyModel),
    ReplaceOne(ReplaceOneModel),
    DeleteOne(DeleteOneModel),
    DeleteMany(DeleteManyModel),
}

/// Inserts a single document.
#[skip_serializing_none]
#[derive(Clone, Debug, Serialize, TypedBuilder)]
#[cfg_attr(test, derive(Deserialize))]
#[serde(rename_all = "camelCase")]
#[builder(field_defaults(default, setter(into)))]
#[non_exhaustive]
pub struct InsertOneModel {
    /// The namespace on which the insert should be performed.
    #[serde(skip_serializing)]
    #[builder(!default)]
    pub namespace: Namespace,

    /// The document to insert.
    #[builder(!default)]
    pub document: Document,
}

impl From<InsertOneModel> for WriteModel {
    fn from(model: InsertOneModel) -> Self {
        Self::InsertOne(model)
    }
}

/// Updates a single document.
#[skip_serializing_none]
#[derive(Clone, Debug, Serialize, TypedBuilder)]
#[cfg_attr(test, derive(Deserialize))]
#[serde(rename_all = "camelCase")]
#[builder(field_defaults(default, setter(into)))]
#[non_exhaustive]
pub struct UpdateOneModel {
    /// The namespace on which the update should be performed.
    #[serde(skip_serializing)]
    #[builder(!default)]
    pub namespace: Namespace,

    /// The filter to use. The first document matching this filter will be updated.
    #[builder(!default)]
    pub filter: Document,

    /// The update to perform.
    #[serde(rename(serialize = "updateMods"))]
    #[builder(!default)]
    pub update: UpdateModifications,

    /// A set of filters specifying to which array elements an update should apply.
    pub array_filters: Option<Array>,

    /// The collation to use.
    pub collation: Option<Document>,

    /// The index to use. Specify either the index name as a string or the index key pattern. If
    /// specified, then the query system will only consider plans using the hinted index.
    pub hint: Option<Bson>,

    /// Whether a new document should be created if no document matches the filter.
    ///
    /// Defaults to false.
    pub upsert: Option<bool>,

    /// Specify which document the operation updates if the query matches multiple
    /// documents. The first document matched by the sort order will be updated.
    pub sort: Option<Document>,
}

impl From<UpdateOneModel> for WriteModel {
    fn from(model: UpdateOneModel) -> Self {
        Self::UpdateOne(model)
    }
}

/// Updates multiple documents.
#[skip_serializing_none]
#[derive(Clone, Debug, Serialize, TypedBuilder)]
#[cfg_attr(test, derive(Deserialize))]
#[serde(rename_all = "camelCase")]
#[builder(field_defaults(default, setter(into)))]
#[non_exhaustive]
pub struct UpdateManyModel {
    /// The namespace on which the update should be performed.
    #[serde(skip_serializing)]
    #[builder(!default)]
    pub namespace: Namespace,

    /// The filter to use. All documents matching this filter will be updated.
    #[builder(!default)]
    pub filter: Document,

    /// The update to perform.
    #[serde(rename(serialize = "updateMods"))]
    #[builder(!default)]
    pub update: UpdateModifications,

    /// A set of filters specifying to which array elements an update should apply.
    pub array_filters: Option<Array>,

    /// The collation to use.
    pub collation: Option<Document>,

    /// The index to use. Specify either the index name as a string or the index key pattern. If
    /// specified, then the query system will only consider plans using the hinted index.
    pub hint: Option<Bson>,

    /// Whether a new document should be created if no document matches the filter.
    ///
    /// Defaults to false.
    pub upsert: Option<bool>,
}

impl From<UpdateManyModel> for WriteModel {
    fn from(model: UpdateManyModel) -> Self {
        Self::UpdateMany(model)
    }
}

/// Replaces a single document.
#[skip_serializing_none]
#[derive(Clone, Debug, Serialize, TypedBuilder)]
#[cfg_attr(test, derive(Deserialize))]
#[serde(rename_all = "camelCase")]
#[builder(field_defaults(default, setter(into)))]
#[non_exhaustive]
pub struct ReplaceOneModel {
    /// The namespace on which the replace should be performed.
    #[serde(skip_serializing)]
    #[builder(!default)]
    pub namespace: Namespace,

    /// The filter to use.
    #[builder(!default)]
    pub filter: Document,

    /// The replacement document.
    #[serde(rename(serialize = "updateMods"))]
    #[builder(!default)]
    pub replacement: Document,

    /// The collation to use.
    pub collation: Option<Document>,

    /// The index to use. Specify either the index name as a string or the index key pattern. If
    /// specified, then the query system will only consider plans using the hinted index.
    pub hint: Option<Bson>,

    /// Whether a new document should be created if no document matches the filter.
    ///
    /// Defaults to false.
    pub upsert: Option<bool>,

    /// Specify which document the operation replaces if the query matches multiple
    /// documents. The first document matched by the sort order will be replaced.
    pub sort: Option<Document>,
}

impl From<ReplaceOneModel> for WriteModel {
    fn from(model: ReplaceOneModel) -> Self {
        Self::ReplaceOne(model)
    }
}

/// Deletes a single document.
#[skip_serializing_none]
#[derive(Clone, Debug, Serialize, TypedBuilder)]
#[cfg_attr(test, derive(Deserialize))]
#[serde(rename_all = "camelCase")]
#[builder(field_defaults(default, setter(into)))]
#[non_exhaustive]
pub struct DeleteOneModel {
    /// The namespace on which the delete should be performed.
    #[serde(skip_serializing)]
    #[builder(!default)]
    pub namespace: Namespace,

    /// The filter to use. The first document matching this filter will be deleted.
    #[builder(!default)]
    pub filter: Document,

    /// The collation to use.
    pub collation: Option<Document>,

    /// The index to use. Specify either the index name as a string or the index key pattern. If
    /// specified, then the query system will only consider plans using the hinted index.
    pub hint: Option<Bson>,
}

impl From<DeleteOneModel> for WriteModel {
    fn from(model: DeleteOneModel) -> Self {
        Self::DeleteOne(model)
    }
}

/// Deletes multiple documents.
#[skip_serializing_none]
#[derive(Clone, Debug, Serialize, TypedBuilder)]
#[cfg_attr(test, derive(Deserialize))]
#[serde(rename_all = "camelCase")]
#[builder(field_defaults(default, setter(into)))]
#[non_exhaustive]
pub struct DeleteManyModel {
    /// The namespace on which the delete should be performed.
    #[serde(skip_serializing)]
    #[builder(!default)]
    pub namespace: Namespace,

    /// The filter to use. All documents matching this filter will be deleted.
    pub filter: Document,

    /// The collation to use.
    pub collation: Option<Document>,

    /// The index to use. Specify either the index name as a string or the index key pattern. If
    /// specified, then the query system will only consider plans using the hinted index.
    pub hint: Option<Bson>,
}

impl From<DeleteManyModel> for WriteModel {
    fn from(model: DeleteManyModel) -> Self {
        Self::DeleteMany(model)
    }
}

impl<T> Collection<T>
where
    T: Send + Sync + Serialize,
{
    /// Constructs an [`InsertOneModel`] with this collection's namespace by serializing the
    /// provided value into a [`Document`]. Returns an error if serialization fails.
    ///
    /// Note that the returned value must be provided to [`bulk_write`](crate::Client::bulk_write)
    /// for the insert to be performed.
    pub fn insert_one_model(&self, document: impl Borrow<T>) -> Result<InsertOneModel> {
        let document = crate::bson_compat::serialize_to_document(document.borrow())?;
        Ok(InsertOneModel::builder()
            .namespace(self.namespace())
            .document(document)
            .build())
    }

    /// Constructs a [`ReplaceOneModel`] with this collection's namespace by serializing the
    /// provided value into a [`Document`]. Returns an error if serialization fails.
    ///
    /// Note that the returned value must be provided to [`bulk_write`](crate::Client::bulk_write)
    /// for the replace to be performed.
    pub fn replace_one_model(
        &self,
        filter: Document,
        replacement: impl Borrow<T>,
    ) -> Result<ReplaceOneModel> {
        let replacement = crate::bson_compat::serialize_to_document(replacement.borrow())?;
        Ok(ReplaceOneModel::builder()
            .namespace(self.namespace())
            .filter(filter)
            .replacement(replacement)
            .build())
    }
}

pub(crate) enum OperationType {
    Insert,
    Update,
    Delete,
}

impl WriteModel {
    pub(crate) fn namespace(&self) -> &Namespace {
        match self {
            Self::InsertOne(model) => &model.namespace,
            Self::UpdateOne(model) => &model.namespace,
            Self::UpdateMany(model) => &model.namespace,
            Self::ReplaceOne(model) => &model.namespace,
            Self::DeleteOne(model) => &model.namespace,
            Self::DeleteMany(model) => &model.namespace,
        }
    }

    pub(crate) fn operation_type(&self) -> OperationType {
        match self {
            Self::InsertOne(_) => OperationType::Insert,
            Self::UpdateOne(_) | Self::UpdateMany(_) | Self::ReplaceOne(_) => OperationType::Update,
            Self::DeleteOne(_) | Self::DeleteMany(_) => OperationType::Delete,
        }
    }

    /// Whether this operation should apply to all documents that match the filter. Returns None if
    /// the operation does not use a filter.
    pub(crate) fn multi(&self) -> Option<bool> {
        match self {
            Self::UpdateMany(_) | Self::DeleteMany(_) => Some(true),
            Self::UpdateOne(_) | Self::ReplaceOne(_) | Self::DeleteOne(_) => Some(false),
            Self::InsertOne(_) => None,
        }
    }

    pub(crate) fn operation_name(&self) -> &'static crate::bson_compat::CStr {
        use crate::bson_compat::cstr;
        match self.operation_type() {
            OperationType::Insert => cstr!("insert"),
            OperationType::Update => cstr!("update"),
            OperationType::Delete => cstr!("delete"),
        }
    }

    /// Constructs the ops document for this write model given the nsInfo array index.
    pub(crate) fn get_ops_document(
        &self,
        ns_info_index: usize,
    ) -> Result<(RawDocumentBuf, Option<Bson>)> {
        // The maximum number of namespaces allowed in a bulkWrite command is much lower than
        // i32::MAX, so this should never fail.
        let index = i32::try_from(ns_info_index)
            .map_err(|_| Error::internal("nsInfo index exceeds i32::MAX"))?;
        let mut ops_document = rawdoc! { self.operation_name(): index };

        if let Self::UpdateOne(UpdateOneModel { update, .. })
        | Self::UpdateMany(UpdateManyModel { update, .. }) = self
        {
            if let UpdateModifications::Document(update_document) = update {
                update_document_check(update_document)?;
            }
        } else if let Self::ReplaceOne(ReplaceOneModel { replacement, .. }) = self {
            replacement_document_check(replacement)?;
        }

        if let Some(multi) = self.multi() {
            ops_document.append(cstr!("multi"), multi);
        }

        if let Self::InsertOne(model) = self {
            let mut insert_document = RawDocumentBuf::try_from(&model.document)?;
            let inserted_id = get_or_prepend_id_field(&mut insert_document)?;
            ops_document.append(cstr!("document"), insert_document);
            Ok((ops_document, Some(inserted_id)))
        } else {
            let model = serialize_to_raw_document_buf(&self)?;
            extend_raw_document_buf(&mut ops_document, model)?;
            Ok((ops_document, None))
        }
    }
}