English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Delete Document in MongoDB

In this chapter, we will learn how to use MongoDB to delete documents.

remove() method

MongoDB'sremove()The method is used to delete documents from the collection. The remove() method accepts two parameters. The first is the deletion condition query, and the second is the justOne flag.

  • query −(optional) The condition for the documents to be deleted.

  • justOne −(optional) If set to true or1Then only one document will be deleted.

Syntax

remove()The basic syntax of the method is as follows-

db.collection.remove(
   <query>,
   <justOne>
)

If your MongoDB is 2.6 The syntax format is as follows for versions later than

db.collection.remove(    <query>,
   {
     justOne: <boolean>,
     writeConcern: <document>
   }
)

Parameter description:

  • query : (optional) The condition for the documents to be deleted.

  • justOne : (optional) If set to true or 1If this parameter is set, only one document will be deleted; if it is not set or the default value false is used, all documents matching the condition will be deleted.

  • writeConcern : (optional) The level of exception thrown.

Example

Assuming that the mycol collection has the following data.

{_id: ObjectId("507f191e810c19729de860e1), title: "MongoDB Overview"},
{_id: ObjectId("507f191e810c19729de860e2), title: "NoSQL Overview"},
{_id: ObjectId("507f191e810c19729de860e3), title: "w3codebox Overview"

The following example will delete all documents with the title 'MongoDB Overview'.

>db.mycol.remove({'title':'MongoDB Overview'})
WriteResult({"nRemoved" :}} 1})
> db.mycol.find()
{"_id" : ObjectId("507f191e810c19729de860e2")}, "title" : "NoSQL Overview"}
{"_id" : ObjectId("507f191e810c19729de860e3"), "title" : "w3codebox Overview

Delete only one document

If there are multiple records and you only want to delete the first record, thenjustOneinremove()method to set parameters.

>db.COLLECTION_NAME.remove(DELETION_CRITERIA,1)

Delete all documents

If you do not specify a deletion condition, MongoDB will delete the entire document from the collection. This is equivalent to the SQL truncate command.

> db.mycol.remove({})
WriteResult({ "nRemoved" : 2 })
> db.mycol.find()
>