Overview
在本指南中,您可以了解如何使用 MongoDB Kotlin 驱动程序删除文档。
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.
要指定排序规则或提示索引,请将DeleteOptions用作deleteOne()和deleteMany()方法的第二个参数。
要在返回的文档上指定排序规则、提示索引、指定排序顺序或指定投影,请将FindOneAndDeleteOptions作为findOneAndDelete()方法的第二个参数。
提示
删除单个文档时,请按唯一索引(例如_id )筛选查询,以确保查询与要删除的文档匹配。
示例文档
以下示例涉及一家销售八种不同颜色油漆的油漆店。 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 }
此数据使用以下 Kotlin 数据类进行建模:
data class PaintOrder( val id: Int, val qty: Int, val color: String )
删除多个文档
油漆店网站显示paint_inventory集合中的所有文档。 为了减少客户混淆,商店希望删除缺货的颜色。
要删除缺货颜色,请查询paint_inventory qty0为 的collection,然后将查询传递给deleteMany() 方法:
val filter = Filters.eq("qty", 0) collection.deleteMany(filter)
下面显示了在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() 示例:完整文件
注意
设置示例
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 the free tier of 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.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
删除文档
商店正在捐赠剩余数量的黄色油漆。 这意味着黄色的qty现在是0 ,我们需要从集合中删除黄色。
要删除黄色,请查询 paint_inventory 集合,其中 color 为 "yellow",并将查询传递给 deleteOne() 方法:
val filter = Filters.eq("color", "yellow") collection.deleteOne(filter)
下面显示了在paint_inventory collection中剩余的文档:
{ "_id": 1, "color": "red", "qty": 5 } { "_id": 2, "color": "purple", "qty": 8 } { "_id": 8, "color": "black", "qty": 8 }
deleteOne() 示例:完整文件
注意
设置示例
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 the free tier of MongoDB Atlas by following the MongoDB Get Started guide.
以下示例是一个完全可运行的文件,它执行以下操作:
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.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 see output similar to the following:
Deleted document count: 1
如果查询筛选器与collection中的文档不匹配,则调用deleteOne()不会删除任何文档并返回以下内容:
Deleted document count: 0
查找和删除文档
该商店希望对剩余数量的紫色颜料进行抽奖,并从paint_inventory collection 中删除紫色。
要选择颜色,请查询paint_inventory color"purple"为 的collection,并将查询传递给findOneAndDelete() 方法。与其他删除方法不同, findOneAndDelete()返回已删除的文档:
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)
注意
如果查询筛选器没有匹配项,则不会删除任何文档,并且该方法会返回null 。
下面显示了在paint_inventory collection中剩余的文档:
{ "_id": 1, "color": "red", "qty": 5 } { "_id": 8, "color": "black", "qty": 8 }
有关本指南中提及的方法和类的更多信息,请参阅以下资源:
deleteOne() API文档
deleteMany() API文档
findOneAndDelete() API文档
DeleteOptions API文档
FindOneAndDeleteOptions API文档
db.collection.deleteOne() MongoDB Server手册条目
db.collection.deleteMany() MongoDB Server手册条目
db.collection.findOneAndDelete() MongoDB Server手册条目