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.
Example
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 theRestaurant
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 }; struct Restaurant { name: String, borough: String, } 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 }; 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