MongoDB Remove() Method – db.Collection.remove()
The remove() method removes documents from the database. It can remove one or all documents from the collection that matches the given query expression. If you pass an empty document({}) in this method, then it will remove all documents from the specified collection. It takes four parameters and returns an object that contains the status of the operation.
- This method uses the default write concern because it uses the delete command and the delete command uses the default write concern. So, if you want to specify a different write concern, then include the write concern in the optional parameter.
- As we know that, this method removes all the documents that match the given matching_criteria, but we want to remove only one document. So, for this situation set the value of justOne option to true to remove only one document.
- You cannot remove capped collections using the remove() method.
- This method can also be used inside a multi-document transaction.
- All the remove() method operations perform for the shared collection that specifies the justOne: true option must contain the shared key/_id field in the query specification. If not then this operation will return error.
Syntax:
db.Collection_name.remove(
<matching_criteria>,
{
justOne: <boolean>,
writeConcern: <document>,
collation: <document>
})
Parameter:
This parameter specifies deletion criteria using query operators. To remove all the documents from the collection, pass an empty document ({}).
Optional Parameters:
- justOne: Its default value is false that deletes all documents according to matching criteria. Set to true if you want to delete only one document.
- 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.
Returns:
This method returns an object that contains the status of the operation.
Examples:
In the following examples, we are working with:
Database: gfg
Collections: student
Document: Three documents contains name and the age of the students
Example 1: Remove all the documents that match the given condition
db.student.remove({name: "Akshay"})
Here, we remove all the documents from the student collection that matches the given condition, i.e, name: “Akshay”.
Example 2: Remove all the documents
db.student.remove({})
Here, we remove all the documents from the student collection by passing empty document(i.e., {}) in the remove() method.
Example 3: Remove only single document
db.student.remove({age:{$eq:18}}, true)
Here, two documents matched the specified condition, but we only want to remove one document, so we set the value of justOne option to true.
Please Login to comment...