Compound Operations
On this page
- Overview
- Sample Data for Examples
- Find and Delete a Document
- Modify Find and Delete Behavior
- Find and Delete Example
- Find and Update a Document
- Modify Find and Update Behavior
- Find and Update Example
- Find and Replace a Document
- Modify Find and Replace Behavior
- Find and Replace Example
- Additional Information
- API Documentation
Overview
In this guide, you can learn how to use the Rust driver to perform compound operations.
Compound operations combine the functionality of read and write operations into one atomic action. If you perform a read operation and a write operation in sequence, someone might change your target document between the operations, leading to unexpected results. When you perform a compound operation, MongoDB prevents intermediate data changes by placing a write lock on the document you are modifying until the operation completes.
You can perform the following compound operations with the driver:
Find and delete one document
Find and update one document
Find and replace one document
This guide includes the following sections:
Sample Data for Examples presents the sample data that is used by the compound operation examples
Find and Delete a Document describes how to find and delete a document in a single operation
Find and Update a Document describes how to find and update a document in a single operation
Find and Replace a Document describes how to find and replace a document in a single operation
Additional Information provides links to resources and API documentation for types and methods mentioned in this guide
Tip
To learn how to perform atomic read and write operations on more than one document at a time, see the Transactions guide.
Sample Data for Examples
The examples in this guide use the following sample documents. Each document represents a student and contains information about their age and the school that they attend:
{ "name": "Alex Johnson", "age": 8, "school": "Lakeside Elementary" }, { "name": "Samara Khan", "age": 11, "school": "Rolling Hills Middle School" }, { "name": "Ben Joseph", "age": 16, "school": "Aurora High School" }, { "name": "Deanna Porowski", "age": 10, "school": "Lakeside Elementary" }
Find and Delete a Document
The find_one_and_delete()
method finds and deletes the first document that
matches the specified query filter. If a document matches the filter
criteria, the method returns a Some
type. If no documents match,
it returns a None
type.
Note
If you want to perform other operations between finding and deleting
a document, you can call the find_one()
method followed by the
delete_one()
method.
Modify Find and Delete Behavior
You can optionally modify the behavior of the find_one_and_delete()
method by passing a FineOneAndDeleteOptions
instance as a parameter.
To use default values for each setting, specify the value None
for
the options parameter.
The following table describes the options available in
FineOneAndDeleteOptions
:
Option | Description |
---|---|
| The maximum amount of time in milliseconds that the query can
run. Type: Duration |
| The projection to use when returning results. Type: Document Default: None |
| The sorting order to use when returning results. By default, the driver
returns documents in their natural order, or as they appear in
the database. To learn more, see natural order
in the Server manual glossary. Type: Document Default: None |
| The write concern for the operation. If you don't set this
option, the operation inherits the write concern set for
the collection. To learn more about write concerns, see
Write Concern in the
Server manual. Type: WriteConcern |
| The collation to use when sorting results. To learn more about collations,
see the Collations guide. Type: Collation Default: None |
| The index to use for the operation. To learn more about
indexes, see Indexes in the Server
manual. This option is available only when connecting to
MongoDB Server versions 4.4 and later. Type: Hint Default: None |
| A map of parameters and values. You can access these parameters
as variables in aggregation expressions. This option is available
only when connecting to MongoDB Server versions 5.0 and later. Type: Document |
| An arbitrary Bson value tied to the operation to trace
it through the database profiler, currentOp , and
logs. This option is available only when connecting to
MongoDB Server versions 4.4 and later.Type: Bson Default: None |
The Rust driver implements the Builder design pattern for the
creation of a FindOneAndDeleteOptions
instance. You can use the
type's builder()
method to construct an options instance by
chaining option builder functions one at a time.
The following code shows how to construct a FindOneAndDeleteOptions
instance and pass it to the find_one_and_delete()
method:
let opts = FindOneAndDeleteOptions::builder().comment(bson!("hello")).build(); let res = my_coll.find_one_and_delete(filter, opts).await?;
Find and Delete Example
The following example uses the find_one_and_delete()
method
to match and delete the first document where the value of the age
field is less than or equal to 10
:
let filter = doc! { "age": doc! { "$lte": 10 } }; let res = my_coll.find_one_and_delete(filter, None).await?; println!("Deleted document:\n{:?}", res);
Deleted document: Some(Document({"_id": ObjectId("..."), "name": String("Deanna Porowski"), "age": Int32(10), "school": String("Lakeside Elementary")}))
Find and Update a Document
The find_one_and_update()
method finds and updates the first
document that matches the specified query filter. The operation updates
the document based on the specifications you provide in an update
document. If a document matches the filter criteria, the method returns
a Some
type. If no documents match, it returns a None
type.
Note
If you want to perform other operations between finding and updating
a document, you can call the find_one()
method followed by the
update_one()
method.
Modify Find and Update Behavior
You can optionally modify the behavior of the find_one_and_update()
method by passing a FindOneAndUpdateOptions
instance as a parameter.
To use default values for each setting, specify the value None
for
the options parameter.
The following table describes the options available in
FineOneAndDeleteOptions
:
Option | Description |
---|---|
| The set of filters specifying the array elements to which the
update applies. Type: Vec<Document> |
| If true , allows the driver to perform a write that violates
document-level validation. To learn more about validation, see
Schema Validation in the Server manual.Type: bool Default: false |
| The maximum amount of time in milliseconds that the query can
run. Type: Duration |
| The projection to use when returning results. Type: Document Default: None |
| If Before , the operation returns the document before the
update. If After , the operation returns the updated document.Type: ReturnDocument Default: ReturnDocument::Before |
| The sorting order to use when returning results. By default, the driver
returns documents in their natural order, or as they appear in
the database. To learn more, see natural order
in the Server manual glossary. Type: Document Default: None |
| If true, the operation inserts a document if no documents match
the query filter. Type: bool Default: false |
| The write concern for the operation. If you don't set this
option, the operation inherits the write concern set for
the collection. To learn more about write concerns, see
Write Concern in the
Server manual. Type: WriteConcern |
| The collation to use when sorting results. To learn more about collations,
see the Collations guide. Type: Collation Default: None |
| The index to use for the operation. To learn more about
indexes, see Indexes in the Server
manual. This option is available only when connecting to
MongoDB Server versions 4.4 and later. Type: Hint Default: None |
| A map of parameters and values. You can access these parameters
as variables in aggregation expressions. This option is available
only when connecting to MongoDB Server versions 5.0 and later. Type: Document |
| An arbitrary Bson value tied to the operation to trace
it through the database profiler, currentOp , and
logs. This option is available only when connecting to
MongoDB Server versions 4.4 and later.Type: Bson Default: None |
The Rust driver implements the Builder design pattern for the
creation of a FindOneAndUpdateOptions
instance. You can use the
type's builder()
method to construct an options instance by
chaining option builder methods one at a time.
The following code shows how to construct a FindOneAndUpdateOptions
instance and pass it to the find_one_and_update()
method:
let opts = FindOneAndUpdateOptions::builder().comment(bson!("hello")).build(); let res = my_coll.find_one_and_update(filter, update, opts).await?;
Find and Update Example
This example shows how to call the find_one_and_update()
method with the
following parameters:
A query filter that matches a document where the value of
school
is"Aurora High School"
An update document that sets the
school
field to"Durango High School"
and increments theage
field by1
A
FindOneAndUpdateOptions
instance that returns the document after the update
let filter = doc! { "school": "Aurora High School" }; let update = doc! { "$set": doc! { "school": "Durango High School" }, "$inc": doc! { "age": 1 } }; let opts = FindOneAndUpdateOptions::builder() .return_document(Some(ReturnDocument::After)) .build(); let res = my_coll.find_one_and_update(filter, update, opts).await?; println!("Updated document:\n{:?}", res);
Updated document: Some(Document({"_id": ObjectId("..."), "name": String("Ben Joseph"), "age": Int32(17), "school": String("Durango High School")}))
Find and Replace a Document
The find_one_and_replace()
method finds and replaces the first
document that matches the specified query filter. The operation replaces
all the fields of the document except the _id
field with fields
and values that you provide. If a document matches the filter criteria,
the method returns a Some
type. If no documents match, it returns a
None
type.
Note
If you want to perform other operations between finding and replacing
a document, you can call the find_one()
method followed by the
replace_one()
method.
Modify Find and Replace Behavior
You can optionally modify the behavior of the find_one_and_replace()
method by passing a FindOneAndReplaceOptions
instance as a parameter.
To use default values for each setting, specify the value None
for
the options parameter.
The following table describes the options available in
FindOneAndReplaceOptions
:
Option | Description |
---|---|
| If true , allows the driver to perform a write that violates
document-level validation. To learn more about validation, see
Schema Validation in the Server manual.Type: bool Default: false |
| The maximum amount of time in milliseconds that the query can
run. Type: Duration |
| The projection to use when returning results. Type: Document Default: None |
| If Before , the operation returns the document before the
update. If After , the operation returns the updated document.Type: ReturnDocument Default: ReturnDocument::Before |
| The sorting order to use when returning results. By default, the driver
returns documents in their natural order, or as they appear in
the database. To learn more, see natural order
in the Server manual glossary. Type: Document Default: None |
| If true, the operation inserts a document if no documents match
the query filter. Type: bool Default: false |
| The write concern for the operation. If you don't set this
option, the operation inherits the write concern set for
the collection. To learn more about write concerns, see
Write Concern in the
Server manual. Type: WriteConcern |
| The collation to use when sorting results. To learn more about collations,
see the Collations guide. Type: Collation Default: None |
| The index to use for the operation. To learn more about
indexes, see Indexes in the Server
manual. This option is available only when connecting to
MongoDB Server versions 4.4 and later. Type: Hint Default: None |
| A map of parameters and values. You can access these parameters
as variables in aggregation expressions. This option is available
only when connecting to MongoDB Server versions 5.0 and later. Type: Document |
| An arbitrary Bson value tied to the operation to trace
it through the database profiler, currentOp , and
logs. This option is available only when connecting to
MongoDB Server versions 4.4 and later.Type: Bson Default: None |
The Rust driver implements the Builder design pattern for the
creation of a FindOneAndReplaceOptions
instance. You can use the
type's builder()
method to construct an options instance by
chaining option builder functions one at a time.
The following code shows how to construct a FindOneAndReplaceOptions
instance and pass it to the find_one_and_replace()
method:
let opts = FindOneAndReplaceOptions::builder().comment(bson!("hello")).build(); let res = my_coll.find_one_and_replace(filter, replacement, opts).await?;
Find and Replace Example
This example shows how to call the find_one_and_replace()
method with the
following parameters:
A query filter that matches a document where the value of
name
includes the string"Johnson"
A replacement document that describes a new student
A
FindOneAndReplaceOptions
instance that returns the document after replacement and projects only thename
andschool
fields in the output
let filter = doc! { "name": doc! { "$regex": "Johnson" } }; let replacement = doc! { "name": "Toby Fletcher", "age": 14, "school": "Durango High School" }; let opts = FindOneAndReplaceOptions::builder() .return_document(Some(ReturnDocument::After)) .projection(doc! { "name": 1, "school": 1, "_id": 0 }) .build(); let res = my_coll.find_one_and_replace(filter, replacement, opts).await?; println!("Document after replacement:\n{:?}", res);
Document after replacement: Some(Document({"name": String("Toby Fletcher"), "school": String("Durango High School")}))
Additional Information
To learn more about the operations in this guide, see the following documentation:
API Documentation
To learn more about the methods and types mentioned in this guide, see the following API documentation: