Overview
In this guide, you can learn how to remove documents with the MongoDB Kotlin driver.
You can remove documents by passing a query filter to the deleteOne(), deleteMany(), or findOneAndDelete() methods:
deleteOne()method: Deletes a single document. If the query filter matches more than one document, the method will remove the first occurrence of a match in the collection.deleteMany()method: Deletes all documents that match the query filter.findOneAndDelete()method: Finds and deletes the first occurrence of a match in the collection. Returns the matched document.
To specify a collation or hint an index, use DeleteOptions as a second parameter to the deleteOne() and deleteMany() methods.
To specify a collation, hint an index, specify sort order, or specify a projection on the returned document, use FindOneAndDeleteOptions as the second parameter to the findOneAndDelete() method.
Tip
When deleting a single document, filter your query by a unique index, such as an _id, to ensure your query matches the document you want to delete.
Sample Documents
The following examples are about a paint store that sells eight different colors of paint. The store had their annual online sale resulting in the following documents in their paint_inventory collection:
{ "_id": 1, "color": "red", "qty": 5 }{ "_id": 2, "color": "purple", "qty": 8 }{ "_id": 3, "color": "blue", "qty": 0 }{ "_id": 4, "color": "white", "qty": 0 }{ "_id": 5, "color": "yellow", "qty": 6 }{ "_id": 6, "color": "pink", "qty": 0 }{ "_id": 7, "color": "green", "qty": 0 }{ "_id": 8, "color": "black", "qty": 8 }This data is modeled with the following Kotlin data class:
data class PaintOrder( val id: Int, val qty: Int, val color: String)Delete Many Documents
The paint store website displays all documents in the paint_inventory collection. To reduce customer confusion, the store wants to remove the colors that are out of stock.
To remove the out of stock colors, query the paint_inventory collection where the qty is 0 and pass the query to the deleteMany() method:
val filter = Filters.eq("qty", 0)collection.deleteMany(filter)The following shows the documents remaining in the paint_inventory collection:
{ "_id": 1, "color": "red", "qty": 5 }{ "_id": 2, "color": "purple", "qty": 8 }{ "_id": 5, "color": "yellow", "qty": 6 }{ "_id": 8, "color": "black", "qty": 8 }deleteMany() Example: Full File
Note
Example Setup
This example connects to an instance of MongoDB by using a connection URI. To learn more about connecting to your MongoDB instance, see the Connect to MongoDB guide. This example also uses the movies collection in the sample_mflix database included in the Atlas sample datasets. You can load them into your database on a free cluster in MongoDB Atlas by following the MongoDB Get Started guide.
The following example is a fully runnable file that finds and deletes all documents in the movies collection that contain a rating of less than 2.9 in the imdb sub-document:
import com.mongodb.MongoExceptionimport com.mongodb.client.model.Filtersimport com.mongodb.kotlin.client.coroutine.MongoClientimport 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()}Delete a Document
The store is donating the remaining quantity of their yellow paint. This means that the qty for yellow is now 0 and we need to remove yellow from the collection.
To remove yellow, query the paint_inventory collection where the color is "yellow" and pass the query to the deleteOne() method:
val filter = Filters.eq("color", "yellow")collection.deleteOne(filter)The following shows the documents remaining in the paint_inventory collection:
{ "_id": 1, "color": "red", "qty": 5 }{ "_id": 2, "color": "purple", "qty": 8 }{ "_id": 8, "color": "black", "qty": 8 }deleteOne() Example: Full File
Note
Example Setup
This example connects to an instance of MongoDB by using a connection URI. To learn more about connecting to your MongoDB instance, see the Connect to MongoDB guide. This example also uses the movies collection in the sample_mflix database included in the Atlas sample datasets. You can load them into your database on a free cluster in MongoDB Atlas by following the MongoDB Get Started guide.
The following example is a fully runnable file that performs the following actions:
Uses the
eq()filter to match movies with thetitleexactly matching the text'The Garbage Pail Kids Movie'.Deletes the single matching document from the
moviescollection.
import com.mongodb.MongoExceptionimport com.mongodb.client.model.Filtersimport com.mongodb.kotlin.client.coroutine.MongoClientimport 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 see output similar to the following:
Deleted document count: 1If 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: 0Find and Delete a Document
The store would like to raffle the remaining quantity of purple paint and remove purple from the paint_inventory collection.
To pick a color, query the paint_inventory collection where the color is "purple" and pass the query to the findOneAndDelete() method. Unlike the other delete methods, findOneAndDelete() returns the deleted document:
val filter = Filters.eq("color", "purple")val result = collection.findOneAndDelete(filter)
println("The following was deleted: $result")The following was deleted: PaintOrder(id=2, qty=8, color=purple)Note
If there are no matches to your query filter, no document gets deleted and the method returns null.
The following shows the documents remaining in the paint_inventory collection:
{ "_id": 1, "color": "red", "qty": 5 } { "_id": 8, "color": "black", "qty": 8 }For more information about the methods and classes mentioned in this guide, see the following resources:
deleteOne() API Documentation
deleteMany() API Documentation
findOneAndDelete() API Documentation
DeleteOptions API Documentation
FindOneAndDeleteOptions API Documentation
db.collection.deleteOne() Server Manual Entry
db.collection.deleteMany() Server Manual Entry
db.collection.findOneAndDelete() Server Manual Entry