Docs Menu

Docs HomeDevelop ApplicationsMongoDB DriversNode.js

Delete a Document

Note

If you specify a callback method, deleteOne() returns nothing. If you do not specify one, this method returns a Promise that resolves to the result object when it completes. See our guide on Promises and Callbacks for more information, or the API documentation for information on the result object.

You can delete a single document in a collection with collection.deleteOne(). The deleteOne() method uses a query document that you provide to match the subset of the documents in the collection that match the query. If you do not provide a query document (or if you provide an empty document), MongoDB matches all documents in the collection and deletes the first match.

You can specify additional query options using the options object passed as the second parameter of the deleteOne method. You can also pass a callback method as an optional third parameter. For more information on this method, see the deleteOne() API documentation.

Note

If your application requires the deleted document after deletion, consider using the collection.findOneAndDelete(). method, which has a similar interface to deleteOne() but also returns the deleted document.

The following snippet deletes a single document from the movies collection. It uses a query document that configures the query to match movies with a title value of "Annie Hall".

Note

This example connects to an instance of MongoDB and uses a sample data database. To learn more about connecting to your MongoDB instance and loading this database, see the Usage Examples guide.

const { MongoClient } = require("mongodb");
// Replace the uri string with your MongoDB deployment's connection string.
const uri =
"mongodb+srv://<user>:<password>@<cluster-url>?writeConcern=majority";
const client = new MongoClient(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
async function run() {
try {
await client.connect();
const database = client.db("sample_mflix");
const movies = database.collection("movies");
// Query for a movie that has title "Annie Hall"
const query = { title: "Annie Hall" };
const result = await movies.deleteOne(query);
if (result.deletedCount === 1) {
console.log("Successfully deleted one document.");
} else {
console.log("No documents matched the query. Deleted 0 documents.");
}
} finally {
await client.close();
}
}
run().catch(console.dir);

If you run the example, you should see output that resembles the following:

Successfully deleted one document.

Because you already deleted the matched document for the query filter, if you attempt to run the example again you should see output that resembles the following:

No documents matched the query. Deleted 0 documents.
←  Delete OperationsDelete Multiple Documents →