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 chaining option builder methods to find_one_and_delete()
. These
builder methods set FindOneAndDeleteOptions
struct fields.
The following table describes the options available in
FindOneAndDeleteOptions
:
Option | Description |
---|---|
max_time | The maximum amount of time in milliseconds that the query can
run. Type: Duration |
projection | The projection to use when returning results. Type: Document Default: None |
sort | 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 |
write_concern | 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 |
collation | The collation to use when sorting results. To learn more about collations,
see the Collations guide. Type: Collation Default: None |
hint | 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 |
let_vars | 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 |
comment | 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 |
Note
Setting Options
You can set FindOneAndDeleteOptions
fields by chaining option builder methods directly
to the find_one_and_delete()
method call. If you're using an earlier version of the driver,
you must construct a FindOneAndDeleteOptions
instance by chaining option builder methods
to the builder()
method. Then, pass your options instance as a parameter to find_one_and_delete()
.
The following code shows how to set the comment
field by chaining
the comment()
method to the find_one_and_delete()
method:
let res = my_coll.find_one_and_delete(filter) .comment(bson!("hello")) .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).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 chaining option builder methods to find_one_and_update()
. These
builder methods set FindOneAndUpdateOptions
struct fields.
The following table describes the options available in
FindOneAndUpdateOptions
:
Option | Description |
---|---|
array_filters | The set of filters specifying the array elements to which the
update applies. Type: Vec<Document> |
bypass_document_validation | 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 |
max_time | The maximum amount of time in milliseconds that the query can
run. Type: Duration |
projection | The projection to use when returning results. Type: Document Default: None |
return_document | If Before , the operation returns the document before the
update. If After , the operation returns the updated document.Type: ReturnDocument Default: ReturnDocument::Before |
sort | 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 |
upsert | If true, the operation inserts a document if no documents match
the query filter. Type: bool Default: false |
write_concern | 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 |
collation | The collation to use when sorting results. To learn more about collations,
see the Collations guide. Type: Collation Default: None |
hint | 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 |
let_vars | 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 |
comment | 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 following code shows how to set the comment
field by chaining
the comment()
method to the find_one_and_update()
method:
let res = my_coll.find_one_and_update(filter, update) .comment(bson!("hello")) .await?;
Find and Update Example
This example shows how to perform the following actions:
Call the
find_one_and_update()
methodPass a query filter to
find_one_and_update()
that matches a document where the value ofschool
is"Aurora High School"
Pass an update document to
find_one_and_update()
that sets theschool
field to"Durango High School"
and increments theage
field by1
Chain the
return_document()
method tofind_one_and_update()
to return the matched 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 res = my_coll.find_one_and_update(filter, update) .return_document(ReturnDocument::After) .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 chaining option builder methods to find_one_and_replace()
. These
builder methods set FindOneAndReplaceOptions
struct fields.
The following table describes the options available in
FindOneAndReplaceOptions
:
Option | Description |
---|---|
bypass_document_validation | 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 |
max_time | The maximum amount of time in milliseconds that the query can
run. Type: Duration |
projection | The projection to use when returning results. Type: Document Default: None |
return_document | If Before , the operation returns the document before the
update. If After , the operation returns the updated document.Type: ReturnDocument Default: ReturnDocument::Before |
sort | 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 |
upsert | If true, the operation inserts a document if no documents match
the query filter. Type: bool Default: false |
write_concern | 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 |
collation | The collation to use when sorting results. To learn more about collations,
see the Collations guide. Type: Collation Default: None |
hint | 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 |
let_vars | 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 |
comment | 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 following code shows how to set the comment
field by chaining
the comment()
method to the find_one_and_replace()
method:
let res = my_coll.find_one_and_replace(filter, replacement) .comment(bson!("hello")) .await?;
Find and Replace Example
This example performs the following actions:
Calls the
find_one_and_replace()
methodPasses a query filter to
find_one_and_replace()
that matches a document where the value ofname
includes the string"Johnson"
Passes a replacement document to
find_one_and_replace()
that describes a new studentChains the
return_document()
method tofind_one_and_replace()
to return the document after replacementChains the
projection()
method tofind_one_and_replace()``to project only the ``name
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 res = my_coll.find_one_and_replace(filter, replacement) .return_document(ReturnDocument::After) .projection(doc! { "name": 1, "school": 1, "_id": 0 }) .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: