Delete Multiple Documents
You can delete multiple documents from a collection in a single operation
by calling the delete_many()
method on a Collection
instance.
Pass a query filter to the delete_many()
method to delete documents in the
collection that match the filter. If you do not include a filter, MongoDB deletes
all the documents in the collection.
The delete_many()
method returns a DeleteResult
type. This type contains information about the delete operation, such as the total
number of documents deleted.
To learn more about delete operations, see the Delete Documents guide.
Tip
To delete all documents in a collection, consider calling the drop()
method on a Collection
instance. To learn more about the drop()
method, see the Drop a Collection section of the Databases and
Collections guide.
Example
This example deletes all documents that match a query filter from the restaurants
collection in the sample_restaurants
database.
This example passes a query filter as a parameter to the delete_many()
method.
The filter matches documents in which the value of the borough
field is "Manhattan"
and the value of the address.street
field is "Broadway"
.
Select the Asynchronous or Synchronous tab to see the corresponding code for each runtime:
use mongodb::{ bson::{ Document, doc }, Client, Collection }; 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! { "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 } }; 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! { "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