Docs Menu
Docs Home
/ / /
Rust Driver
/

Delete a Document

You can delete a document from a collection by calling the delete_one() method on a Collection instance.

Pass a query filter to the delete_one() method to match the document you want to delete from the collection. If multiple documents match the query filter, MongoDB deletes the first matching document according to their natural order in the database or according to the sort order specified in a DeleteOptions instance.

The delete_one() method returns a DeleteResult type. This type contains information about the result of the delete operation, such as the total number of documents deleted.

To learn more about delete operations, see the Delete Documents guide.

This example deletes a document that matches a query filter from the restaurants collection in the sample_restaurants database.

This example uses a query filter that matches documents in which the value of the name field is "Haagen-Dazs" and the borough field is "Brooklyn". MongoDB deletes the first document that matches the query filter.

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

use mongodb::{
bson::{ Document, doc },
Client,
Collection
};
#[tokio::main]
async fn main() -> mongodb::error::Result<()> {
let uri = "<connection string>";
let client = Client::with_uri_str(uri).await?;
let my_coll: Collection<Document> = 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 }
};
fn main() -> mongodb::error::Result<()> {
let uri = "<connection string>";
let client = Client::with_uri_str(uri)?;
let my_coll: Collection<Document> = 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

Back

Replace a Document