Docs Menu

Delete Documents

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 filter to specify which documents to delete.

Note

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 = context.services.get("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" };
itemsCollection.deleteOne(query)
.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 } };
itemsCollection.deleteMany(query)
.then(result => console.log(`Deleted ${result.deletedCount} item(s).`))
.catch(err => console.error(`Delete failed with error: ${err}`))
Give Feedback
© 2021 MongoDB, Inc.

About

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