delete

Definition

  • delete

New in version 2.6.

The delete command removes documents from a collection.A single delete command can contain multiple deletespecifications. The command cannot operate on cappedcollections. The remove methods providedby the MongoDB drivers use this command internally.

The delete command has the following syntax:

  1. {
  2. delete: <collection>,
  3. deletes: [
  4. { q : <query>, limit : <integer>, collation: <document> },
  5. { q : <query>, limit : <integer>, collation: <document> },
  6. { q : <query>, limit : <integer>, collation: <document> },
  7. ...
  8. ],
  9. ordered: <boolean>,
  10. writeConcern: { <write concern> }
  11. }

The command takes the following fields:

FieldTypeDescriptiondeletestringThe name of the target collection.deletesarrayAn array of one or more delete statements to perform in the namedcollection.orderedbooleanOptional. If true, then when a delete statement fails, return withoutperforming the remaining delete statements. If false, then when adelete statement fails, continue with the remaining deletestatements, if any. Defaults to true.writeConcerndocumentOptional. A document expressing the write concernof the delete command. Omit to use the default writeconcern.

Do not explicitly set the write concern for the operation if run ina transaction. To use write concern with transactions, seeTransactions and Write Concern.

Each element of the deletes array contains the following fields:

FieldTypeDescriptionqdocumentThe query that matches documents to delete.limitintegerThe number of matching documents to delete. Specify either a 0 todelete all matching documents or 1 to delete a single document.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.

Returns:A document that contains the status of the operation.See Output for details.

Behavior

Limits

The total size of all the queries (i.e. the q field values) in thedeletes array must be less than or equal to the maximumBSON document size.

The total number of delete documents in the deletes array must beless than or equal to the maximum bulk size.

Transactions

delete 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

Limit the Number of Documents Deleted

The following example deletes from the orders collection onedocument that has the status equal to D by specifying thelimit of 1:

  1. db.runCommand(
  2. {
  3. delete: "orders",
  4. deletes: [ { q: { status: "D" }, limit: 1 } ]
  5. }
  6. )

The returned document shows that the command deleted 1 document.See Output for details.

  1. { "ok" : 1, "n" : 1 }

Delete All Documents That Match a Condition

The following example deletes from the orders collection alldocuments that have the status equal to D by specifying thelimit of 0:

  1. db.runCommand(
  2. {
  3. delete: "orders",
  4. deletes: [ { q: { status: "D" }, limit: 0 } ],
  5. writeConcern: { w: "majority", wtimeout: 5000 }
  6. }
  7. )

The returned document shows that the command found and deleted 13documents. See Output for details.

  1. { "ok" : 1, "n" : 13 }

Delete All Documents from a Collection

Delete all documents in the orders collection by specifying anempty query condition and a limit of 0:

  1. db.runCommand(
  2. {
  3. delete: "orders",
  4. deletes: [ { q: { }, limit: 0 } ],
  5. writeConcern: { w: "majority", wtimeout: 5000 }
  6. }
  7. )

The returned document shows that the command found and deleted 35documents in total. See Output for details.

  1. { "ok" : 1, "n" : 35 }

Bulk Delete

The following example performs multiple delete operations on theorders collection:

  1. db.runCommand(
  2. {
  3. delete: "orders",
  4. deletes: [
  5. { q: { status: "D" }, limit: 0 },
  6. { q: { cust_num: 99999, item: "abc123", status: "A" }, limit: 1 }
  7. ],
  8. ordered: false,
  9. writeConcern: { w: 1 }
  10. }
  11. )

The returned document shows that the command found and deleted 21documents in total for the two delete statements. SeeOutput for details.

  1. { "ok" : 1, "n" : 21 }

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.runCommand({
  2. delete: "myColl",
  3. deletes: [
  4. { q: { category: "cafe", status: "a" }, limit: 0, collation: { locale: "fr", strength: 1 } }
  5. ]
  6. })

Output

The returned document contains a subset of the following fields:

  • delete.ok
  • The status of the command.
  • delete.n
  • The number of documents deleted.
  • delete.writeErrors
  • An array of documents that contains information regarding any errorencountered during the delete operation. ThewriteErrors array contains an error document foreach delete statement that errors.

Each error document contains the following information:

  • delete.writeErrors.index
  • An integer that identifies the delete statement in thedeletes array, which uses a zero-based index.

  • delete.writeErrors.code

  • An integer value identifying the error.

  • delete.writeErrors.errmsg

  • A description of the error.
  • delete.writeConcernError
  • Document that describe error related to write concern and containsthe field:

    • delete.writeConcernError.code
    • An integer value identifying the cause of the write concern error.

    • delete.writeConcernError.errmsg

    • A description of the cause of the write concern error.

The following is an example document returned for a successfuldelete command:

  1. { ok: 1, n: 1 }

The following is an example document returned for a deletecommand that encountered an error:

  1. {
  2. "ok" : 1,
  3. "n" : 0,
  4. "writeErrors" : [
  5. {
  6. "index" : 0,
  7. "code" : 10101,
  8. "errmsg" : "can't remove from a capped collection: test.cappedLog"
  9. }
  10. ]
  11. }