Skip to main content

Delete Documents

Delete API is used to delete existing documents that match the filters.

Example collection

The first step is to set up the collection object. All the operations on the collection are performed through this collection object.

const catalog = db.getCollection<Catalog>("catalog");

Now let's assume an e-commerce website that has the above collection catalog and has 5 products(documents) present in it.

idnamepricebrandlabelspopularityreviews
1fiona handbag99.9michael korspurses8{"author": "alice", "rating": 7}
2tote bag49coachhandbags9{"author": "olivia", "rating": 8.3}
3sling bag75coachpurses9{"author": "alice", "rating": 9.2}
4sneakers shoes40adidasshoes10{"author": "olivia", "rating": 9}
5running shoes89nikeshoes10{"author": "olivia", "rating": 8.5}

Delete one

A simple delete is by filtering on the primary key of the document. Let's say you need to remove a product from this collection that has an id assigned as 5.

const deleteResponse = await catalog.deleteOne({
filter: { id: 5 },
});

Delete many

Extending single document delete example, in case the products that you are planning to remove have continuous ids then you can use range delete to remove these products. As an example, if you need to delete documents that have id greater than or equal to 3 but less than 5.

const deleteResponse = await catalog.deleteMany({
filter: {
"$and": [
{
id: {
"$lt": 5,
}
},
{
id: {
"$gte": 3,
}
}
],
}
});

Delete All

Sometimes, there is a need to delete all the documents then an empty filter can be sent to the server.

const deleteResponse = await catalog.deleteMany({
filter: {}
});