db.collection.remove()

Definition

  • db.collection.remove()

mongo Shell Method

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

Removes documents from a collection.

The db.collection.remove() method can have one of twosyntaxes. The remove() method can take aquery document and an optional justOne boolean:

  1. db.collection.remove(
  2. <query>,
  3. <justOne>
  4. )

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

New in version 2.6.

  1. db.collection.remove(
  2. <query>,
  3. {
  4. justOne: <boolean>,
  5. writeConcern: <document>,
  6. collation: <document>
  7. }
  8. )

ParameterTypeDescriptionquerydocumentSpecifies deletion criteria using query operators. To delete all documents in a collection,pass an empty document ({}).

Changed in version 2.6: In previous versions, the method invoked with no query parameterdeleted all documents in a collection.

justOnebooleanOptional. To limit the deletion to just one document, set to true. Omit touse the default value of false and delete all documents matchingthe deletion criteria.writeConcerndocumentOptional. 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 ina transaction. To use write concern with transactions, seeTransactions and Write Concern.collationdocumentOptional.

Specifies the collation to use for the operation.

Collation allows users to specifylanguage-specific rules for string comparison, such as rules forlettercase and accent marks.

The collation option has the following syntax:

  1. collation: {
  2. locale: <string>,
  3. caseLevel: <boolean>,
  4. caseFirst: <string>,
  5. strength: <int>,
  6. numericOrdering: <boolean>,
  7. alternate: <string>,
  8. maxVariable: <string>,
  9. backwards: <boolean>
  10. }

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

If the collation is unspecified but the collection has adefault collation (see db.createCollection()), theoperation uses the collation specified for the collection.

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

You cannot specify multiple collations for an operation. Forexample, you cannot specify different collations per field, or ifperforming a find with a sort, you cannot use one collation for thefind and another for the sort.

New in version 3.4.

Changed in version 2.6: The remove() returns an object thatcontains the status of the operation.

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

Behavior

Write Concern

Changed in version 2.6.

The remove() method uses thedelete 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 documentsthat match the query expression. Specify the justOne option tolimit the operation to removing a single document. To delete a singledocument sorted by a specified order, use the findAndModify() method.

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

Capped Collections

You cannot use the remove() methodwith a capped collection.

Sharded Collections

All remove() operations for a shardedcollection that specify the justOne option must include theshard keyor the _id field in the query specification.remove() operations specifying justOnein a sharded collection which do not contain either theshard 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 ina transaction. To use write concern with transactions, seeTransactions and Write Concern.

Important

In most cases, multi-document transaction incurs a greaterperformance cost over single document writes, and theavailability of multi-document transactions should not be areplacement for effective schema design. For many scenarios, thedenormalized data model (embedded documents and arrays) will continue to be optimal for yourdata and use cases. That is, for many scenarios, modeling your dataappropriately will minimize the need for multi-documenttransactions.

For additional transactions usage considerations(such as runtime limit and oplog size limit), see alsoProduction 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 bioscollection:

  1. db.bios.remove( { } )

This operation is not equivalent to thedrop() method.

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

Remove All Documents that Match a Condition

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

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

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

Override Default Write Concern

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

Changed in version 3.0: In previous versions, majority referred to the majority of allmembers of the replica set instead of the majority of the votingmembers.

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

Remove a Single Document that Matches a Condition

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

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

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

Specify Collation

New in version 3.4.

Collation allows users to specifylanguage-specific rules for string comparison, such as rules forlettercase and accent marks.

A collection myColl has the following documents:

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

The following operation includes the collationoption:

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

WriteResult

Changed in version 2.6.

Successful Results

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

  1. WriteResult({ "nRemoved" : 4 })

See also

WriteResult.nRemoved

Write Concern Errors

If the remove() method encounters writeconcern errors, the results include theWriteResult.writeConcernError field:

  1. WriteResult({
  2. "nRemoved" : 21,
  3. "writeConcernError" : {
  4. "code" : 64,
  5. "errInfo" : {
  6. "wtimeout" : true
  7. },
  8. "errmsg" : "waiting for replication timed out"
  9. }
  10. })

See also

WriteResult.hasWriteConcernError()

Errors Unrelated to Write Concern

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

  1. WriteResult({
  2. "nRemoved" : 0,
  3. "writeError" : {
  4. "code" : 2,
  5. "errmsg" : "unknown top level operator: $invalidFieldName"
  6. }
  7. })

See also

WriteResult.hasWriteError()