Navigation

db.collection.remove()

Definition

db.collection.remove()

mongo Shell Method

This page documents the mongo shell method, and does not refer to the MongoDB Node.js driver (or any other driver) method. For corresponding MongoDB driver API, refer to your specific MongoDB driver documentation instead.

Removes documents from a collection.

The db.collection.remove() method can have one of two syntaxes. The remove() method can take a query document and an optional justOne boolean:

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

Or the method can take a query document and an optional remove options document:

db.collection.remove(
   <query>,
   {
     justOne: <boolean>,
     writeConcern: <document>,
     collation: <document>
   }
)
Parameter Type Description
query document Specifies deletion criteria using query operators. To delete all documents in a collection, pass an empty document ({}).
justOne boolean Optional. To limit the deletion to just one document, set to true. Omit to use the default value of false and delete all documents matching the deletion criteria.
writeConcern document

Optional. A document expressing the write concern. Omit to use the default write concern. See Write Concern.

Do not explicitly set the write concern for the operation if run in a transaction. To use write concern with transactions, see Transactions and Write Concern.

collation document

Optional.

Specifies the collation to use for the operation.

Collation allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks.

The collation option has the following syntax:

collation: {
   locale: <string>,
   caseLevel: <boolean>,
   caseFirst: <string>,
   strength: <int>,
   numericOrdering: <boolean>,
   alternate: <string>,
   maxVariable: <string>,
   backwards: <boolean>
}

When specifying collation, the locale field is mandatory; all other collation fields are optional. For descriptions of the fields, see Collation Document.

If the collation is unspecified but the collection has a default collation (see db.createCollection()), the operation uses the collation specified for the collection.

If no collation is specified for the collection or for the operations, MongoDB uses the simple binary comparison used in prior versions for string comparisons.

You cannot specify multiple collations for an operation. For example, you cannot specify different collations per field, or if performing a find with a sort, you cannot use one collation for the find and another for the sort.

New in version 3.4.

The remove() returns an object that contains the status of the operation.

Returns:A WriteResult object that contains the status of the operation.

Behavior

Write Concern

The remove() method uses the delete command, which uses the default write concern. To specify a different write concern, include the write concern in the options parameter.

Query Considerations

By default, remove() removes all documents that match the query expression. Specify the justOne option to limit the operation to removing a single document. To delete a single document sorted by a specified order, use the findAndModify() method.

When removing multiple documents, the remove operation may interleave with other read and/or write operations to the collection.

Capped Collections

You cannot use the remove() method with a capped collection.

Sharded Collections

All remove() operations for a sharded collection that specify the justOne: true option must include the shard key or the _id field in the query specification. remove() operations specifying justOne: true in a sharded collection which do not contain either the shard key or the _id field return an error.

Transactions

db.collection.remove() can be used inside multi-document transactions.

Do not explicitly set the write concern for the operation if run in a transaction. To use write concern with transactions, see Transactions and Write Concern.

Important

In most cases, multi-document transaction incurs a greater performance cost over single document writes, and the availability of multi-document transactions should not be a replacement for effective schema design. For many scenarios, the denormalized data model (embedded documents and arrays) will continue to be optimal for your data and use cases. That is, for many scenarios, modeling your data appropriately will minimize the need for multi-document transactions.

For additional transactions usage considerations (such as runtime limit and oplog size limit), see also Production Considerations.

Examples

The following are examples of the remove() method.

Remove All Documents from a Collection

To remove all documents in a collection, call the remove method with an empty query document {}. The following operation deletes all documents from the bios collection:

db.bios.remove( { } )

This operation is not equivalent to the drop() method.

To remove all documents from a collection, it may be more efficient to use the drop() method to drop the entire collection, including the indexes, and then recreate the collection and rebuild the indexes.

Remove All Documents that Match a Condition

To remove the documents that match a deletion criteria, call the remove() method with the <query> parameter:

The following operation removes all the documents from the collection products where qty is greater than 20:

db.products.remove( { qty: { $gt: 20 } } )

Override Default Write Concern

The following operation to a replica set removes all the documents from the collection products where qty is greater than 20 and specifies a write concern of "w: majority" with a wtimeout of 5000 milliseconds such that the method returns after the write propagates to a majority of the voting replica set members or the method times out after 5 seconds.

db.products.remove(
    { qty: { $gt: 20 } },
    { writeConcern: { w: "majority", wtimeout: 5000 } }
)

Remove a Single Document that Matches a Condition

To remove the first document that match a deletion criteria, call the remove method with the query criteria and the justOne parameter set to true or 1.

The following operation removes the first document from the collection products where qty is greater than 20:

db.products.remove( { qty: { $gt: 20 } }, true )

Specify Collation

New in version 3.4.

Collation allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks.

A collection myColl has the following documents:

{ _id: 1, category: "café", status: "A" }
{ _id: 2, category: "cafe", status: "a" }
{ _id: 3, category: "cafE", status: "a" }

The following operation includes the collation option:

db.myColl.remove(
   { category: "cafe", status: "A" },
   { collation: { locale: "fr", strength: 1 } }
)

WriteResult

Successful Results

The remove() returns a WriteResult object that contains the status of the operation. Upon success, the WriteResult object contains information on the number of documents removed:

WriteResult({ "nRemoved" : 4 })

Write Concern Errors

If the remove() method encounters write concern errors, the results include the WriteResult.writeConcernError field:

WriteResult({
  "nRemoved" : 7,
  "writeConcernError" : {
    "code" : 64,
    "codeName" : "WriteConcernFailed",
    "errmsg" : "waiting for replication timed out",
    "errInfo" : {
      "wtimeout" : true,
      "writeConcern" : {    // Added in MongoDB 4.4
        "w" : "majority",
        "wtimeout" : 1,
        "provenance" : "getLastErrorDefaults"
      }
    }
  }
})

Errors Unrelated to Write Concern

If the remove() method encounters a non-write concern error, the results include WriteResult.writeError field:

WriteResult({
   "nRemoved" : 0,
   "writeError" : {
      "code" : 2,
      "errmsg" : "unknown top level operator: $invalidFieldName"
   }
})