Quick Start: Node.js & MongoDB - How to Delete Documents

Lauren Schaefer

Quick Start Node.js and MongoDB

Welcome (or welcome back!) to the Quick Start with MongoDB and Node.js series! So far we’ve covered how to connect to a database, create documents, read documents, and update documents.

Today, let’s tackle the final CRUD operation: delete. We’ll discover how to delete a single document as well as delete many documents in a single operation.

Get started with an M0 cluster on Atlas today. It's free forever, and it’s the easiest way to try out the steps in this blog series.

Delete a Document

Let’s begin by deleting a single Airbnb listing in the listingsAndReviews collection. If you’re new to this series, check out the earlier post where we dove into the details of how data is stored in this sample database.

We can delete a single document by calling Collection’s deleteOne(). deleteOne() has one required parameter: a filter of type object. The filter is used to select the document to delete. You can think of the filter as essentially the same as the query param we used in findOne() and the filter param we used in updateOne(). You can include zero properties in the filter to search for all documents in the collection, or you can include one or more properties to narrow your search.

deleteOne() also has an optional options param. See the deleteOne() docs for more information on these options.

deleteOne() will delete the first document that matches the given query. Even if more than one document matches the query, only one document will be deleted. If you do not specify a filter, the first document found in natural order will be deleted.

Let’s say we want to delete an Airbnb listing with a particular name. We can use deleteOne() to achieve this. We’ll include the name of the listing in the filter param. We can create a function to delete a listing with a particular name.

async function deleteListingByName(client, nameOfListing) {
    result = await client.db("sample_airbnb").collection("listingsAndReviews")
         .deleteOne({ name: nameOfListing });
    console.log(`${result.deletedCount} document(s) was/were deleted.`);

Let’s say we want to delete the Airbnb listing we created in a previous post that has the name “Cozy Cottage.” We can call deleteListingsByName() by passing a connected MongoClient and the name “Cozy Cottage.”

await deleteListingByName(client, "Cozy Cottage");

Executing the command above results in the following output.

1 document(s) was/were deleted.

Deleting Many Documents

Sometimes you’ll want to delete more than one document at a time. In this case, you can use Collection’s deleteMany(). Like deleteOne(), deleteMany() requires that you pass a filter of type object. You can choose to include options of type object as well.

Let’s say we want to remove documents that have not been updated recently. We can call deleteMany() with a filter that searches for documents that were scraped prior to a particular date. Our function will look like the following.

async function deleteListingsScrapedBeforeDate(client, date) {
    result = await client.db("sample_airbnb").collection("listingsAndReviews")
        .deleteMany({ "last_scraped": { $lt: date } });
    console.log(`${result.deletedCount} document(s) was/were deleted.`);

To delete listings that were scraped prior to February 15, 2019, we can call deleteListingsScrapedBeforeDate() with a connected MongoClient and a Date instance that represents February 15.

await deleteListingsScrapedBeforeDate(client, new Date("2019-02-15"));

Executing the command above will result in the following output.

606 document(s) was/were deleted.

Now only recently scraped documents are in our collection.

Wrapping Up

This post included many code snippets that built on code written in the first post of this MongoDB and Node.js Quick Start series. To get a full copy of the code used in today’s post, visit the Node.js Quick Start GitHub Repo.

Be on the lookout for the next post in this series where we’ll discuss the basics of the aggregation pipeline.

Series Versions

The examples in this article were created with the following application versions:

ComponentVersion used
MongoDB Node.js Driver3.3.2

All posts in the Quick Start: Node.js and MongoDB series: