Delete Documents


The code snippets on this page demonstrate how to delete documents that are stored in a MongoDB collection. Delete operations use a query filter to specify which documents to delete.


Data Lake data sources do not support write operations.

Data Model

The examples on this page use a collection named store.items that models various items available for purchase in an online store. Each item has a name, an inventory quantity, and an array of customer reviews.

// store.items
    "_id": { "bsonType": "objectId" },
    name: { "bsonType": "string" },
    quantity: { "bsonType": "int" },
    reviews: {
      "bsonType": "array",
      "items": {
        "username": { "bsonType": "string" },
        "comment": { "bsonType": "string" }

Snippet Setup

To use a code snippet in a function, you must first instantiate a MongoDB collection handle:

exports = function() {
  const mongodb ="mongodb-atlas");
  const itemsCollection = mongodb.db("store").collection("items");
  const purchasesCollection = mongodb.db("store").collection("purchases");
  // ... paste snippet here ...


Delete a Single Document

You can delete a single document from a collection using the collection.deleteOne() action.

The following function snippet deletes one document in the items collection that has a name value of lego:

const query = { "name": "lego" };

  .then(result => console.log(`Deleted ${result.deletedCount} item.`))
  .catch(err => console.error(`Delete failed with error: ${err}`))

Delete One or More Documents

You can delete multiple items from a collection using the collection.deleteMany() action.

The following snippet deletes all documents in the items collection that do not have any reviews:

const query = { "reviews": { "$size": 0 } };

  .then(result => console.log(`Deleted ${result.deletedCount} item(s).`))
  .catch(err => console.error(`Delete failed with error: ${err}`))