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.
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()
.
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.MongoExceptionimport com.mongodb.client.model.Filtersimport com.mongodb.kotlin.client.coroutine.MongoClientimport kotlinx.coroutines.runBlockingdata class Movie(val imdb: IMDB){ data class IMDB(val rating: Double)}fun main() = runBlocking { 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:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4