Absolutely, deleting documents in Node.js with MongoDB is straightforward. Here's a breakdown of the methods you can use:
Deleting a Single Document:
-
Use the
deleteOne()method on your collection object. -
Pass a query document as the first argument to specify the document to delete. This document acts like a filter.
-
If no query document is provided, or an empty one is used, the first matching document in the collection gets deleted.
Code Example (deleteOne):
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
async function deleteDocument() {
try {
await client.connect();
const database = client.db("myDatabase");
const collection = database.collection("myCollection");
const filter = { name: "John Doe" }; // Replace with your filter criteria
const result = await collection.deleteOne(filter);
console.log(`${result.deletedCount} document(s) deleted`);
} catch (error) {
console.error(error);
} finally {
await client.close();
}
}
deleteDocument();
Deleting Multiple Documents:
-
Use the
deleteMany()method on your collection object. -
Similar to
deleteOne(), it takes a query document as the first argument to specify documents to delete. -
This method removes all documents matching the criteria in the query document.
Code Example (deleteMany):
async function deleteManyDocuments() {
try {
await client.connect();
const database = client.db("myDatabase");
const collection = database.collection("myCollection");
const filter = { age: { $gt: 30 } }; // Replace with your filter criteria
const result = await collection.deleteMany(filter);
console.log(`${result.deletedCount} document(s) deleted`);
} catch (error) {
console.error(error);
} finally {
await client.close();
}
}
deleteManyDocuments();
Additional Considerations:
-
Remember to connect to your MongoDB instance before performing any operations.
-
For both methods, the
deletedCountproperty in the result object indicates the number of documents deleted. -
If you need to retrieve the deleted document along with deletion, consider using
findOneAndDelete()instead.
These examples provide a basic understanding of deleting documents in Node.js with MongoDB. You can explore the official MongoDB Node.js driver documentation for more details and advanced functionalities https://www.mongodb.com/docs/manual/reference/method/db.collection.deleteOne/.