Navigation

db.collection.deleteOne()

Definition

db.collection.deleteOne()

Removes a single document from a collection.

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

Specifies deletion criteria using query operators.

Specify an empty document { } to delete the first document returned in the collection.

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

Deletion Order

deleteOne deletes the first document that matches the filter. Use a field that is part of a unique index such as _id for precise deletions.

Capped Collections

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

Examples

Delete a Single Document

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 the order with _id: ObjectId("563237a41a4d68582c2509da") :

try {
   db.orders.deleteOne( { "_id" : ObjectId("563237a41a4d68582c2509da") } );
} catch (e) {
   print(e);
}

The operation returns:

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

The following operation deletes the first document with expiryts greater than ISODate("2015-11-01T12:40:15Z")

try {
   db.orders.deleteOne( { "expiryts" : { $lt: ISODate("2015-11-01T12:40:15Z") } } );
} catch (e) {
   print(e);
}

The operation returns:

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

deleteOne() with Write Concern

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

try {
   db.orders.deleteOne(
       { "_id" : ObjectId("563237a41a4d68582c2509da") },
       { 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"
})

See also

To delete multiple documents, see db.collection.deleteMany()