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.
package usage.examples; import static com.mongodb.client.model.Filters.eq; import org.bson.Document; import org.bson.conversions.Bson; import com.mongodb.MongoException; import com.mongodb.client.MongoClient; import com.mongodb.client.MongoClients; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import com.mongodb.client.result.DeleteResult; public class DeleteOne { public static void main(String[] args) { // Replace the uri string with your MongoDB deployment's connection string String uri = "<connection string uri>"; try (MongoClient mongoClient = MongoClients.create(uri)) { MongoDatabase database = mongoClient.getDatabase("sample_mflix"); MongoCollection<Document> collection = database.getCollection("movies"); Bson query = eq("title", "The Garbage Pail Kids Movie"); try { DeleteResult result = collection.deleteOne(query); System.out.println("Deleted document count: " + result.getDeletedCount()); } catch (MongoException me) { System.err.println("Unable to delete due to an error: " + me); } } } }
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
Tip
Legacy API
If you are using the legacy API, see our FAQ page to learn what changes you need to make to this code example.
For additional information on the classes and methods mentioned on this page, see the following API Documentation: