OPTIONS

db.collection.deleteMany()

Definition

db.collection.deleteMany()

Removes all documents that match the filter from a collection.

db.collection.deleteMany(
   <filter>,
   {
      writeConcern: <document>
   }
)
Parameter Type Description
filter document

Specifies deletion criteria using query operators.

To delete all documents in a collection, pass in an empty document ({ }).

writeConcern document Optional. A document expressing the write concern. Omit to use the default write concern.
Returns:A document containing:
  • A boolean acknowledged as true if the operation ran with write concern or false if write concern was disabled
  • deletedCount containing the number of deleted documents

Behavior

Capped Collections

deleteMany() throws a WriteError exception if used on a capped collection. To remove all documents from a capped collection, use db.collection.drop() instead.

Delete a Single Document

To delete a single document, use db.collection.deleteOne() instead.

Alternatively, use a field that is a part of a unique index such as _id.

Examples

Delete Multiple Documents

The orders collection has documents with the following structure:

{
   _id: ObjectId("563237a41a4d68582c2509da"),
   stock: "Brent Crude Futures",
   qty: 250,
   type: "buy-limit",
   limit: 48.90
   creationts: ISODate("2015-11-01T12:30:15Z"),
   expiryts: ISODate("2015-11-01T12:35:15Z"),
   client: "Crude Traders Inc."
}

The following operation deletes all documents where client : "Crude Traders Inc.":

try {
   db.orders.deleteMany( { "client" : "Crude Traders Inc." } );
}
catch (e) {
   print (e);
}

The operation returns:

{ "acknowledged" : true, "deletedCount" : 10 }

The following operation deletes all documents where stock : "Brent Crude Futures" and limit is greater than 48.88:

try {
   db.orders.deleteMany( { "stock" : "Brent Crude Futures", "limit" : { $gt : 48.88 } } );
}
catch (e) {
   print (e);
}

The operation returns:

{ "acknowledged" : true, "deletedCount" : 8 }

deleteMany() with Write Concern

Given a three member replica set, the following operation specifies a w of majority and wtimeout of 100:

try {
   db.orders.deleteMany(
       { "client" : "Crude Traders Inc." },
       { w : "majority", wtimeout : 100 }
   );
}
catch (e) {
   print (e);
}

If the acknowledgement takes longer than the wtimeout limit, the following exception is thrown:

WriteConcernError({
   "code" : 64,
   "errInfo" : {
      "wtimeout" : true
   },
   "errmsg" : "waiting for replication timed out"
})

Was this page helpful?

Yes No

Thank you for your feedback!

We're sorry! You can Report a Problem to help us improve this page.