Delete Multiple Documents
You can delete multiple documents from a collection in a single operation
by calling the deleteMany()
method on a MongoCollection
object.
To specify which documents to delete, pass a query filter that matches
the documents you want to delete. If you provide an empty document,
MongoDB matches all documents in the collection and deletes them. While
you can use deleteMany()
to delete all documents in a collection,
consider using the drop()
method instead for better performance.
Upon successful deletion, this method returns an instance of
DeleteResult
. You can retrieve information such as the number of
documents deleted by calling the getDeletedCount()
method on the
DeleteResult
instance.
If your delete operation fails, the driver raises an exception. For more
information on the types of exceptions raised under specific conditions,
see the API documentation for deleteMany()
, linked at the bottom of
this page.
Example
The following snippet deletes multiple documents from the movies
collection in the sample_mflix
database.
The query filter passed to the deleteMany()
method matches all
movie documents that contain a rating
of less than 1.9 in the imdb
subdocument.
Note
This example connects to an instance of MongoDB using a connection URI. To learn more about connecting to your MongoDB instance, see the connection guide.
package usage.examples; import static com.mongodb.client.model.Filters.lt; import org.bson.Document; import org.bson.conversions.Bson; import com.mongodb.MongoException; import com.mongodb.client.MongoClient; import com.mongodb.client.MongoClients; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import com.mongodb.client.result.DeleteResult; public class DeleteMany { public static void main(String[] args) { // Replace the uri string with your MongoDB deployment's connection string String uri = "<connection string uri>"; try (MongoClient mongoClient = MongoClients.create(uri)) { MongoDatabase database = mongoClient.getDatabase("sample_mflix"); MongoCollection<Document> collection = database.getCollection("movies"); Bson query = lt("imdb.rating", 1.9); try { DeleteResult result = collection.deleteMany(query); System.out.println("Deleted document count: " + result.getDeletedCount()); } catch (MongoException me) { System.err.println("Unable to delete due to an error: " + me); } } } }
When you run the example, you should see output that reports the number of
documents deleted in your call to deleteMany()
.
Deleted document count: 4
Tip
Legacy API
If you are using the legacy API, see our FAQ page to learn what changes you need to make to this code example.
For additional information on the classes and methods mentioned on this page, see the following API Documentation: