Overview
In this guide, you can learn how to use the Scala driver to remove documents from a MongoDB collection by performing delete operations.
A delete operation removes one or more documents from a MongoDB collection. You can perform a delete operation by using the deleteOne() or deleteMany() methods.
Sample Data
The examples in this guide use the restaurants collection in the sample_restaurants database from the Atlas sample datasets. To access this collection from your Scala application, create a MongoClient that connects to an Atlas cluster and assign the following values to your database and collection variables:
val database: MongoDatabase = mongoClient.getDatabase("sample_restaurants") val collection: MongoCollection[Document] = database.getCollection("restaurants")
To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the MongoDB Get Started guide.
Delete Operations
You can perform delete operations in MongoDB by using the following methods:
deleteOne(), which deletes the first document that matches the search criteriadeleteMany(), which deletes all documents that match the search criteria
Each delete method requires a query filter document, which specifies the search criteria that determine which documents to select for removal. To learn more about query filters, see the Specify a Query guide.
Delete One Document
The following example uses the deleteOne() method to remove a document in which the value of the name field is "Happy Garden":
val filter = equal("name", "Happy Garden") val observable: Observable[DeleteResult] = collection.deleteOne(filter) observable.subscribe(new Observer[DeleteResult] { override def onNext(result: DeleteResult): Unit = println(s"Deleted document count: ${result.getDeletedCount}") override def onError(e: Throwable): Unit = println(s"Error: $e") override def onComplete(): Unit = println("Completed") })
Deleted document count: 1 Completed
Delete Multiple Documents
The following example uses the deleteMany() method to remove all documents in which the value of the borough field is "Brooklyn" and the value of the name field is "Starbucks":
val filter = and( equal("borough", "Brooklyn"), equal("name", "Starbucks") ) val observable: Observable[DeleteResult] = collection.deleteMany(filter) observable.subscribe(new Observer[DeleteResult] { override def onNext(result: DeleteResult): Unit = println(s"Deleted document count: ${result.getDeletedCount}") override def onError(e: Throwable): Unit = println(s"Error: $e") override def onComplete(): Unit = println("Completed") })
Deleted document count: 3 Completed
Customize the Delete Operation
The deleteOne() and deleteMany() methods optionally accept a DeleteOptions parameter, which represents options you can use to configure the delete operation. If you don't specify any options, the driver performs the delete operation with default settings.
The following table describes the setter methods that you can use to configure a DeleteOptions instance:
Method | Description |
|---|---|
| Specifies the kind of language collation to use when sorting results. For more information, see Collation in the MongoDB Server manual. |
| Specifies the index to use when matching documents.
For more information, see the hint
option in the |
| Specifies the index as a string to use when matching documents. For more information, see the hint option in the `` delete`` reference page of the MongoDB Server manual. |
| Provides a map of parameter names and values to set top-level
variables for the operation. Values must be constant or closed
expressions that don't reference document fields. For more information,
see the let option in the |
| Sets a comment to attach to the operation. For more
information, see the Command
Fields section in the |
Modify Delete Example
The following code creates options and uses the comment() method to add a comment to the delete operation. Then, the example uses the deleteMany() method to delete all documents in the restaurants collection in which the value of the name field includes the string "Red".
val filter = regex("name", "Red") val opts = DeleteOptions().comment("sample comment") val observable = collection.deleteMany(filter, opts) observable.subscribe(new Observer[DeleteResult] { override def onNext(result: DeleteResult): Unit = println(s"Deleted document count: ${result.getDeletedCount}") override def onError(e: Throwable): Unit = println(s"Error: $e") override def onComplete(): Unit = println("Completed") })
Deleted document count: 124 Completed
Tip
If you use the the deleteOne() method in the preceding example instead of the deleteMany() method, the driver deletes only the first document that matches the query filter.
Return Value
The deleteOne() and deleteMany() methods each return a DeleteResult instance. You can access the following information from a DeleteResult instance:
deletedCount, which indicates the number of documents deletedwasAcknowledged(), which returnstrueif the server acknowledges the result
If the query filter does not match any documents, the driver doesn't delete any documents, and the value of deletedCount is 0.
Note
If the wasAcknowledged() method returns false, trying to access the deletedCount property results in an InvalidOperation exception. The driver cannot determine these values if the server does not acknowledge the write operation.
API Documentation
To learn more about any of the methods or types discussed in this guide, see the following API documentation: