MongoDB Delete document

Sneha Mallik
Last Updated: May 13, 2022

Introduction

The data in MongoDB has a flexible schema. We do not need to declare the new columns of a collection in MongoDB before entering data into the database, as we would in a traditional RDBMS(Relational Database Management System). So, when developing a schema in MongoDB, there are a few basic things to keep in mind.

  • We need to create a schema that meets our needs.
  • If we use two items together, we must merge them into a single object.
  • Joins can be performed while the data is being written.
  • Our schema has to be optimized for the most common data searches.
  • We can handle even the most complicated data aggregation tasks.

Document

In MongoDB, a document is the fundamental data unit, which is relatively similar to a row in relational databases.

A document is a collection of keys with data or values associated with them. Every programming language has its own representation of these documents, although the basic structure of these documents is usually a map, hash, or dictionary. In JavaScript, a document is an object, just like in the example below.

 

Document in the collection

{"message" : "Hello, MongoDB"}

 

The key "message" in the above document sample has the value "Hello, MongoDB." Most documents have a more comprehensive structure that includes several and nested key-value pairs. A document's key is often made up of string data. Instead, there are always some notable exceptions in the key.

There are no null characters in the key. If a null character appears in a key, it implies the key has ended.

Some special characters (such as $ or .) are reserved for specific situations. These are reserved characters.

Collection

According to the RDBMS concept, a collection in MongoDB can be regarded as a Table. The collection is essentially a gathering of documents. Dynamic schemas are always present in MongoDB collections. This means that documents in a single collection might have a wide variety of elements and shapes. 

 

For example:

[
  {
    _id: ObjectId("61a8f4b791f30e5db6642602"),
    name: 'Sapna',
    phoneNumber: '456654456'
  },
  {
    _id: ObjectId("61a8f59d91f30e5db6642603"),
    name: 'Samir',
    phoneNumber: '123321123'
  },
  {
    _id: ObjectId("61a8f5dd91f30e5db6642604"),
    name: 'Aman',
    phoneNumber: '456654676'
  }
]

 

To know more about creating databases, collections, and documents in MongoDB, refer here

MongoDB Delete Document

We can delete a document from any collection using one of four MongoDB Delete methods.

These are the four methods:

  • deleteOne()
  • deleteMany()
  • findOneAndDelete()
  • remove()

 

To delete or remove a document from the MongoDB collection, use any of the methods listed above.

deleteOne() Method

In a MongoDB collection, the deleteOne method is used to delete a single document. We only have four parameters to use to figure out what to remove from the collection.

Syntax:

db.collection_name.deleteOne(
selection_criteria:<document>,
{
    writeConcern: <document>,
    collation: <document>,
    hint: <document|string>
})
query: This is the delete method's selection criteria, or you could call it a filter. If you wish to remove a student’s age from a collection based on their name, the name is the selection criteria or filter. The other parameters are optional.

Parameters:

Parameter

Description

writeConcern

This parameter is used when you don't want to utilize the default write concern. This parameter has the type of document.

collation

It describes how the collation will be used in operations. Users can set language-specific string comparison criteria, such as rules for letter case and accent marks. This parameter has the type of document.

hint

It's a document or field that provides the index that will be used to support the filter. It can accept an index specification document or an index name string, and it will return an error if you specify an index that does not exist.

 

Return:

Field

Description

deleteCount

The deleteCount field contains the total number of documents that have been removed.

acknowledged

If write concern was enabled, the value of this field is true; otherwise, it is false. It’s a boolean field.

 

Deletes only one document that matches a specific filter, even if the supplied filter matches many documents. For example:-

db.students.deleteOne({phoneNumber : 123321123}

 

Output

The ‘Output’ shows the collection after running the query, and we can see that the document having the phone number ‘123321123’ has been deleted. Now only 2 documents remain.

deleteMany() Method

deleteMany() is a function for removing several items from a list. Pass an empty filter document{} to the db.collection.deleteMany() function to delete all documents from a collection. 

Syntax:

db.collection_name.deleteMany(
  <filter>,
  {
      writeConcern: <document>,
      collation: <document>
  }
)

 

Parameters:

Parameter

Description

writeConcern

This parameter is used when you don't want to utilize the default write concern. This parameter has the type of document.

collation

It describes how the collation will be used in operations. Users can set language-specific string comparison criteria, such as rules for letter case and accent marks. This parameter has the type of document.

 

Return:

This function will return a document with a boolean value of true (if the write concern has been enabled) or false (if the write concern has been disabled) and a deletedCount value that reflects the total number of documents deleted.

 

Deletes all documents that match a filter we provide. For example:-

db.students.deleteMany({phoneNumber : 456654456})

 

Output

The ‘Output’ shows the collection after running the query, and we can see that the document having the phone number ‘456654456’ has been deleted. Now only 1 document is remaining.

findOneAndDelete() Method

The findOneAndDelete() option allows you to delete the first document ordered in the order you specify.

Syntax:

db.collection_name.findOneAndDelete(
  <filter>,
  {
    projection: <document>,
    sort: <document>,
    maxTimeMS: <number>,
    collation: <document>
  }
)

 

Parameters:

Parameter

Description

projection

It only allows you to select the information you need rather than the entire document.

sort

It determines the order in which the documents that match the selection criteria are sorted: the values 1 and -1 sort in ascending order and descending order, respectively.

maxTimeMS

It's the maximum amount of time the query can run for.

collation

It describes how the collation will be used in operations. Users can set language-specific string comparison criteria, such as rules for letter case and accent marks. This parameter has the type of document.

 

Return:

  • This method returns the deleted document if a document matches the provided filter query.
  • This method returns null if no document matches the specified filter query.

For example:-

db.students.findOneAndDelete({phoneNumber : 456654676})

 

Output

The ‘Output’ shows the collection after running the query, and we can see that the document having the phone number ‘456654676’ has been deleted. Now we can see that the collection is empty now.

remove() Method

The db.colloction.remove() property is commonly used in MongoDB to delete documents from a collection. 

The remove() method has two parameters to work with:-

  1. Deletion criteria: You can remove documents from the collection using its syntax.
  2. JustOne: Whenever set to true or 1, it eliminates only one document.

Syntax:

db.collection_name.remove(
<matching_criteria>,
{
    justOne: <boolean>,
    writeConcern: <document>,
    collation: <document>
})

 

Parameters:

Parameter

Description

justOne

The default value is false here, which means it deletes all documents that fit the criteria. If you just wish to delete one document, set it to true.

writeConcern

This parameter is used when you don't want to utilize the default write concern. This parameter has the type of document.

collation

It describes how the collation will be used in operations. Users can set language-specific string comparison criteria, such as rules for letter case and accent marks. This parameter has the type of document.

 

Return:

This function returns an object containing the operation's status.

 

To remove all the documents.

Pass an empty query document to the delete() method to remove all documents from a collection. The indexes are not removed by the remove() method.

Let's look at an example of the delete() method in action. We remove all documents from the "collection_name" collection in this example.

db.collection_name.remove({})

 

To remove all the documents that match a condition.

Call the remove() function with the <query> parameter to delete documents that match a specific condition.

When the type field in the "collection_name" collection equals “MongoDB update and delete”, the following example will remove all documents from the collection.

db.collection_name.remove({type:"MongoDB update and delete"})

 

To remove a single document that matches a condition.

Call the remove() function with the justOne argument set to true or 1 to remove a single document that matches a particular requirement.

The following example removes a single document from the "collection_name" collection whose type field equals “MongoDB update and delete”.

db.collection_name.remove({type:"MongoDB update and delete"}, 1)

Frequently Asked Questions

 

  1. Explain what is meant by MongoDB delete.

Ans: MongoDB Delete: To delete documents from a collection in MongoDB, use the db.colloction.remove() method.

Syntax:

db.collection_name.remove (deletion_criteria)

 

2. What is the difference between deleteMany() and "remove() in MongoDB?

Ans:

  • deleteMany() in MongoDB 

It removes all documents from a collection that matches the filter. Query operators are used to provide the deletion criteria. We have to pass in an empty document ({ }) to delete all documents in a collection.

  • remove() in MongoDB 

All documents that match the query expression are removed with remove().

Difference: In MongoDB 3.2, the deleteMany() method was added to align the mongo shell CRUD API with the driver API. The remove() operation is a historical interface supported for backward compatibility.

The differences are also in the values that are returned.

With deleteMany(), it returns:

> db.collectionName.deleteMany({"name": "Apples"})
{ "acknowledged" : true, "deletedCount" : 5 }

 

With remove(), it returns:

> db.collectionName.remove({"name": "Apples"})
WriteResult({ "nRemoved" : 5 })

Key Takeaways

In this blog, we went over the concept of MongoDB deleteThe deleteOne method removes a single document from a MongoDB collection. We also learned how to use the filter to delete a specific document from a collection.

Enroll in our Full Stack Web Development Course — MERN Stack to deeply understand the concept of MongoDB delete in Web Development. 

Credits: GIPHY

Happy Developing!

Was this article helpful ?
0 upvotes

Comments

No comments yet

Be the first to share what you think