Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

MongoDB – db.collection.deleteone()

  • Last Updated : 09 Feb, 2021

The deleteOne() method deletes the first document from the collection that matches the given selection criteria. It will delete/remove a single document from the collection. It takes four parameters, the first parameter is the selection criteria and the others are optional. If you use this method in the chapped collection, then this method will give a WriteError exception, so to delete documents from the chapped collection use drop() method. If you use this method in shared collection, then the query expression passed in this method must contain the shared key/_id field, if not then this method will give an error. You can also use this method in multi-document transactions.

Syntax:

db.Collection_name.deleteOne(

selection_criteria:<document>,

{



    writeConcern: <document>,

    collation: <document>,

    hint: <document|string>

})

Parameter:

  • The first parameter is the selection criteria. The type of this parameter is document.
  • Other parameters are optional.

Optional Parameter:

  • writeConcern: It is only used when you do not want to use the default write concern. The type of this parameter is a document.
  • Collation: It specifies the use of the collation for operations. It allows users to specify the language-specific rules for string comparison like rules for lettercase and accent marks. The type of this parameter is a document.
  • hint: It is a document or field that specifies the index to use to support the filter. It can take an index specification document or the index name string and if you specify an index that does not exist, then it will give an error.

Return:

This method returns a document that contains the following fields:



  • acknowledged: It is a boolean field, if the value of this field is true then the operation run with write concern. If the value of this field is false, then the operation runs without write concern.
  • deleteCount: This field contains the total number of deleted documents.

Examples:

In the following examples, we are working with:

Database: gfg

Collections: student

Document: Four documents contains the name and the age of the students

  • Delete the first matched document whose age is 17:
db.student.deleteOne({age:17})

Here, we delete the first document that matches the filter query(i.e., age:17) from the student collection using deleteOne() method.

After deletion:

  • Delete the first matched document whose age is less than 18:
db.student.deleteOne({age:{$lt:18}})

Here, we delete the first document that matches the filter query(i.e., {age:{$lt:18}}) from the student collection using the deleteOne() method.

Note: $lt operator means less than.

After deletion:

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!