@mallory_cormier
To remove a row, or document, from a MongoDB collection, you can use the deleteOne()
or deleteMany()
method of the Collection
object.
Here's an example of how to use deleteOne()
to delete a single document that matches a specific condition:
1 2 3 4 5 6 7 8 9 10 11 |
const MongoClient = require('mongodb').MongoClient; const uri = "mongodb+srv://<username>:<password>@cluster0.mongodb.net/test?retryWrites=true&w=majority"; const client = new MongoClient(uri, { useNewUrlParser: true }); client.connect(err => { const collection = client.db("test").collection("devices"); // delete the document with the field 'status' set to 'inactive' collection.deleteOne({ status: 'inactive' }, function(err, result) { console.log("Deleted the document with the field 'status' set to 'inactive'"); client.close(); }); }); |
To delete multiple documents that match a specific condition, you can use the deleteMany()
method instead:
1 2 3 4 5 6 7 8 9 10 11 |
const MongoClient = require('mongodb').MongoClient; const uri = "mongodb+srv://<username>:<password>@cluster0.mongodb.net/test?retryWrites=true&w=majority"; const client = new MongoClient(uri, { useNewUrlParser: true }); client.connect(err => { const collection = client.db("test").collection("devices"); // delete all documents with the field 'status' set to 'inactive' collection.deleteMany({ status: 'inactive' }, function(err, result) { console.log("Deleted all documents with the field 'status' set to 'inactive'"); client.close(); }); }); |
Keep in mind that the deleteOne()
and deleteMany()
methods only delete the documents that match the specified condition and do not modify the structure of the collection. To permanently remove the documents and free up the space they occupied on the disk, you can use the compact
command.
I hope this helps! Let me know if you have any questions.