Delete a Document
You can delete a single document from a collection using the deleteOne()
method on a MongoCollection
object. The method accepts a query filter
that matches the document you want to delete. If you do not specify
a filter, MongoDB matches the first document in the collection. The
deleteOne()
method only deletes the first document matched.
This method returns an instance of DeleteResult
which contains information
including how many documents were deleted as a result of the operation.
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 deleteOne()
, linked at the bottom of
this page.
Example
The following snippet deletes a single document from the movies
collection of the sample_mflix
database. The example uses the eq()
filter to match movies with the title
exactly matching the text
'The Garbage Pail Kids Movie'
.
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 title: String) 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.eq(Movie::title.name, "The Garbage Pail Kids Movie") try { val result = collection.deleteOne(query) println("Deleted document count: " + result.deletedCount) } catch (e: MongoException) { System.err.println("Unable to delete due to an error: $e") } mongoClient.close() }
When you run the example, if the query filter you passed in your call to
deleteOne()
matches a document and removes it, you should see output
that looks something like this:
Deleted document count: 1
If your query filter does not match a document in your collection,
your call to deleteOne()
removes no documents and returns the following:
Deleted document count: 0
For additional information on the classes and methods mentioned on this page, see the following API Documentation: