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 2.9
in the imdb
sub-document.
When you run the example, you should see output that reports the number of
documents deleted in your call to deleteMany()
.
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.
import com.mongodb.MongoException import com.mongodb.client.model.Filters import com.mongodb.kotlin.client.coroutine.MongoClient import kotlinx.coroutines.runBlocking data class Movie(val imdb: IMDB){ data class IMDB(val rating: Double) } fun main() = runBlocking { // Replace the uri string with your MongoDB deployment's connection string val uri = "<connection string uri>" val mongoClient = MongoClient.create(uri) val database = mongoClient.getDatabase("sample_mflix") val collection = database.getCollection<Movie>("movies") val query = Filters.lt("${Movie::imdb.name}.${Movie.IMDB::rating.name}", 2.9) try { val result = collection.deleteMany(query) println("Deleted document count: " + result.deletedCount) } catch (e: MongoException) { System.err.println("Unable to delete due to an error: $e") } mongoClient.close() }
Deleted document count: 4
For additional information on the classes and methods mentioned on this page, see the following API Documentation: