Docs Menu

Delete Documentsicons/link.png

On this page

  • Overview
  • Data Model
  • Snippet Setup
  • Methods
  • Delete a Single Document
  • Delete One or More Documents

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


Data Lake data sources do not support write operations.

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" }

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 ...

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}`))

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}`))
Give Feedback
MongoDB logo
© 2021 MongoDB, Inc.


  • Careers
  • Investor Relations
  • Legal Notices
  • Privacy Notices
  • Security Information
  • Trust Center
© 2021 MongoDB, Inc.