Join us at MongoDB.local London on 7 May to unlock new possibilities for your data. Use WEB50 to save 50%.
Register now >
Docs Menu
Docs Home
/ /

Delete Documents

In this guide, you can learn how to remove documents from your MongoDB collections using delete operations.

This guide includes the following sections:

  • Sample Data for Examples presents the sample data that is used by the delete operation example

  • Delete Operations describes how to use the driver to execute delete operations

  • Delete Examples provides code examples for the delete operations

  • Additional Information provides links to resources and API documentation for types and methods mentioned in this guide

The example in this guide uses the following sample documents. Each document represents an item in a store's inventory and contains information about its categorization and unit price:

{ "item": "trowel", "category": "garden", "unit_price": 9.89 },
{ "item": "placemat", "category": "kitchen", "unit_price": 3.19 },
{ "item": "watering can", "category": "garden", "unit_price": 11.99 }

The Rust driver provides the delete_one() and delete_many() methods to perform delete operations.

The delete_one() and delete_many() methods take a query filter as a parameter. A query filter consists of the fields and values that form criteria for documents to match.

You can modify the behavior of the delete operation methods by chaining option builder methods to delete_one() and delete_many(). These option methods set DeleteOptions struct fields.

Note

Setting Options

You can set DeleteOptions fields by chaining option builder methods directly to the delete method call. If you're using an earlier version of the driver, you must construct an DeleteOptions instance by chaining option builder methods to the builder() method. Then, pass your options instance as a parameter to delete_one() or delete_many().

The following table describes the options available in DeleteOptions:

Option
Description

collation

The collation to use when sorting results. To learn more about collations, see the Collations guide.

Type: Collation
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

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. These parameters can be accessed 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 delete_one() method:

let res = my_coll
.delete_one(filter)
.comment(bson!("hello!"))
.await?;

The delete_one() and delete_many() methods return a DeleteResult type. This type contains the deleted_count property, which describes the number of documents deleted. If no documents match the query filter you specified, the delete operation does not remove any documents, and the value of deleted_count is 0.

This section provides code examples for the following delete operations:

The following example uses the delete_one() method to delete a document that has an item value of "placemat":

let filter = doc! { "item": "placemat" };
let res = my_coll.delete_one(filter).await?;
println!("Deleted documents: {}", res.deleted_count);
Deleted documents: 1

This example deletes a document that matches a query filter from the restaurants collection in the sample_restaurants database. The delete_one() method deletes the first document in which the value of the name field is "Haagen-Dazs" and the borough field is "Brooklyn".

You can access the documents in the restaurants collection as instances of the Document type or a custom data type. To specify which data type represents the collection's data, replace the <T> type parameter on the highlighted line with one of the following values:

  • <Document>: Accesses collection documents as BSON documents

  • <Restaurant>: Accesses collection documents as instances of the Restaurant struct, defined at the top of the code

Select the Asynchronous or Synchronous tab to see the corresponding code for each runtime:

use mongodb::{
bson::{ Document, doc },
Client,
Collection
};
use serde::{ Deserialize, Serialize };
#[derive(Serialize, Deserialize, Debug)]
struct Restaurant {
name: String,
borough: String,
}
#[tokio::main]
async fn main() -> mongodb::error::Result<()> {
let uri = "<connection string>";
let client = Client::with_uri_str(uri).await?;
// Replace <T> with the <Document> or <Restaurant> type parameter
let my_coll: Collection<T> = client
.database("sample_restaurants")
.collection("restaurants");
let filter =
doc! { "$and": [
doc! { "name": "Haagen-Dazs" },
doc! { "borough": "Brooklyn" }
]
};
let result = my_coll.delete_one(filter).await?;
println!("Deleted documents: {}", result.deleted_count);
Ok(())
}
Deleted documents: 1
use mongodb::{
bson::{ Document, doc },
sync::{ Client, Collection }
};
use serde::{ Deserialize, Serialize };
#[derive(Serialize, Deserialize, Debug)]
struct Restaurant {
name: String,
borough: String,
}
fn main() -> mongodb::error::Result<()> {
let uri = "<connection string>";
let client = Client::with_uri_str(uri)?;
// Replace <T> with the <Document> or <Restaurant> type parameter
let my_coll: Collection<T> = client
.database("sample_restaurants")
.collection("restaurants");
let filter =
doc! { "$and": [
doc! { "name": "Haagen-Dazs" },
doc! { "borough": "Brooklyn" }
]
};
let result = my_coll.delete_one(filter).run()?;
println!("Deleted documents: {}", result.deleted_count);
Ok(())
}
Deleted documents: 1

This example performs the following actions:

  • Calls the delete_many() method

  • Passes a query filter to delete_many() that matches documents where the value of category is "garden"

  • Chains the hint() method to delete_many() to use the _id_ index as the hint for the delete operation

let filter = doc! { "category": "garden" };
let hint = Hint::Name("_id_".to_string());
let res = my_coll
.delete_many(filter)
.hint(hint)
.await?;
println!("Deleted documents: {}", res.deleted_count);
Deleted documents: 2

Note

If you use the delete_one() method instead of delete_many() in the preceding code example, the driver deletes only the first of the two documents that match the query filter.

This example deletes all documents that match a query filter from the restaurants collection in the sample_restaurants database. The delete_many() method deletes documents in which the value of the borough field is "Manhattan" and the value of the address.street field is "Broadway".

You can access the documents in the restaurants collection as instances of the Document type or a custom data type. To specify which data type represents the collection's data, replace the <T> type parameter on the highlighted line with one of the following values:

  • <Document>: Accesses collection documents as BSON documents

  • <Restaurant>: Accesses collection documents as instances of the Restaurant struct, defined at the top of the code

Select the Asynchronous or Synchronous tab to see the corresponding code for each runtime:

use mongodb::{
bson::{ Document, doc },
Client,
Collection
};
use serde::{ Deserialize, Serialize };
#[derive(Debug, Serialize, Deserialize)]
struct Address {
street: String,
city: String,
}
#[derive(Serialize, Deserialize, Debug)]
struct Restaurant {
name: String,
borough: String,
address: Address,
}
#[tokio::main]
async fn main() -> mongodb::error::Result<()> {
let uri = "<connection string>";
let client = Client::with_uri_str(uri).await?;
// Replace <T> with the <Document> or <Restaurant> type parameter
let my_coll: Collection<T> = client
.database("sample_restaurants")
.collection("restaurants");
let filter =
doc! { "$and": [
doc! { "borough": "Manhattan" },
doc! { "address.street": "Broadway" }
]
};
let result = my_coll.delete_many(filter).await?;
println!("Deleted documents: {}", result.deleted_count);
Ok(())
}
// Your values might differ
Deleted documents: 615
use mongodb::{
bson::{ Document, doc },
sync::{ Client, Collection }
};
use serde::{ Deserialize, Serialize };
#[derive(Debug, Serialize, Deserialize)]
struct Address {
street: String,
city: String,
}
#[derive(Serialize, Deserialize, Debug)]
struct Restaurant {
name: String,
borough: String,
address: Address,
}
fn main() -> mongodb::error::Result<()> {
let uri = "<connection string>";
let client = Client::with_uri_str(uri)?;
// Replace <T> with the <Document> or <Restaurant> type parameter
let my_coll: Collection<T> = client
.database("sample_restaurants")
.collection("restaurants");
let filter =
doc! { "$and": [
doc! { "borough": "Manhattan" },
doc! { "address.street": "Broadway" }
]
};
let result = my_coll.delete_many(filter).run()?;
println!("Deleted documents: {}", result.deleted_count);
Ok(())
}
// Your values might differ
Deleted documents: 615

To learn more about the operations in this guide, see the following documentation:

To learn more about the methods and types mentioned in this guide, see the following API documentation:

Back

Update Arrays

On this page