MongoDB – Delete Document

MongoDB – Delete Document

In this chapter, we will learn how to delete a document using MongoDB.

The remove() Method

MongoDB's remove() method is used to remove a document from the collection. remove() method accepts two parameters. One is deletion criteria and second is justOne flag.

  • deletion criteria − (Optional) deletion criteria according to documents will be removed.
  • justOne − (Optional) if set to true or 1, then remove only one document.
  • deletion criteria − (Optional) deletion criteria according to documents will be removed.
    justOne − (Optional) if set to true or 1, then remove only one document.

    Syntax

    Basic syntax of remove() method is as follows −

    >db.COLLECTION_NAME.remove(DELLETION_CRITTERIA)

    Example

    Consider the stuDetails collection has the following data.

    > db.stuDetails.find()
    { "_id" : 0, "name" : "aimee Zank", "class" : 10 }
    { "_id" : 1, "name" : "Aurelia Menendez", "class" : 10 }
    { "_id" : 2, "name" : "Salena Olmos", "class" : 10 }

    Following example will remove all the documents whose name is 'Salena Olmos'.

    > db.stuDetails.remove({"name":"Salena Olmos"})
    WriteResult({ "nRemoved" : 1 })
    > db.stuDetails.find()
    { "_id" : 0, "name" : "aimee Zank", "class" : 10 }
    { "_id" : 1, "name" : "Aurelia Menendez", "class" : 10 }
    >

    Remove Only One

    If there are multiple records and you want to delete only the first record, then set justOne parameter in remove() method.

    >db.COLLECTION_NAME.remove(DELETION_CRITERIA,1)

    Remove All Documents

    If you don't specify deletion criteria, then MongoDB will delete whole documents from the collection. This is equivalent of SQL's truncate command.

    > db.stuDetails.remove({})
    WriteResult({ "nRemoved" : 2 })
    >
MongoDB – Update Document (Prev Lesson)
(Next Lesson) MongoDB – Projection