Delete operation

The delete operation removes a document from the database when a given query is met. Two methods for deleting documents in a collection include deleteOne() and deleteMany().

Delete a single document

The deleteOne() method removes a single document (the first document that matches the query parameter) completely from the collection.

  1. db.collection.deleteOne({<query_params>})

Insert the following list of documents:

  1. db.scientists.insertMany([
  2. {
  3. firstname: 'Thomas',
  4. lastname: 'Edison',
  5. born: 1847,
  6. invention: 'LightBulb',
  7. nobel: true
  8. },
  9. {
  10. firstname: 'Graham',
  11. lastname: 'Bell',
  12. born: 1847,
  13. invention: 'telephone',
  14. nobel: false
  15. },
  16. {
  17. firstname: 'Nikola',
  18. lastname: 'Tesla',
  19. born: 1856,
  20. invention: 'Tesla coil',
  21. nobel: false
  22. },
  23. {
  24. firstname: 'Ada',
  25. lastname: 'Lovelace',
  26. born: 1815,
  27. invention: 'Computer programming',
  28. nobel: false
  29. }
  30. ])

This operation returns a response showing acknowledged as true and the ObjectId of the four inserted documents:

  1. {
  2. acknowledged: true,
  3. insertedIds: {
  4. '0': ObjectId("63470121d7a4a1b0b38eb2df"),
  5. '1': ObjectId("63470121d7a4a1b0b38eb2e0"),
  6. '2': ObjectId("63470121d7a4a1b0b38eb2e1"),
  7. '3': ObjectId("63470121d7a4a1b0b38eb2e2")
  8. }
  9. }

Next, delete a document from the collection where the field nobel is set to false.

  1. db.scientists.deleteOne({ nobel: false })

This operation returns a response that shows that a single document was deleted from the collection.

  1. { acknowledged: true, deletedCount: 1 }

Deletes multiple documents

To delete multiple documents at once, use the deleteMany() method. Using the same record from earlier, let’s delete all the documents with nobel set to false.

  1. db.scientists.deleteMany({ nobel: false })

This command removes all the documents in the collection that matches the query.