How to remove a field from a document in MongoDB

In this MongoDB tutorial, we are going to discuss “MongoDB remove a field from the document”. We will also cover this with different operations and examples. These are the following topics that we are going to cover in this tutorial:

  • How to remove a field from the documents in MongoDB
  • MongoDB remove fields from the document
  • MongoDB remove a field from the documents matching query
  • Remove a field from the documents using MongoDB compass
  • MongoDB remove a field from one document
  • MongoDB remove a field from all documents
  • Remove a field from the documents using python

How to remove a field from the documents in MongoDB

In MongoDB, The $unset operator is used to delete or remove a particular field. Consider the following syntax:

{ $unset: { <field1>: "", ... } }

When we define the value in the $unset expression does not impact the operation. If you want to specify an <field> in an embedded document or an array use dot (.) notation.

If the field does not exist in the documents then $unset does nothing. The update() operation uses the $unset operator to remove the fields. You will more understand with the help of an example so let’s get started;

Example:

In this example, we use the update() operation that uses the $unset operator to remove the field from the first document.

The following documents were inserted into the items collection.

db.items.insertMany([
{"_id": 1, "item": "almonds", "description": "almond clusters", "instock": 120, "Review": true },
{"_id": 2, "item": "bread", "description": "raisin and nut bread", "instock": 80, "Review": true },
{"_id": 3, "item": "pecans", "description": "candied pecans", "instock": 60 }
])

After inserting the documents use the below query to remove the field from the first document.

db.items.update( { }, { $unset: { Review: " " }} )

In the update() operation { } is used to specify the document field which you want to update. By default, it selects the first document. The $unset operator will update and remove the Review field from the first document.

How to remove the field from the document in MongoDB
Remove a field from the document in MongoDB

We successfully remove a field from the documents. The find() method is used to return all the documents of the collection.

Read: Create index in MongoDB

MongoDB remove fields from the document

We can remove multiple fields from the documents. Like if we want to remove a field from all the documents field then we use the updateMany() method.

The updateMany() method will check all the documents of the collection and the $unset operator will remove all the defined fields.

You will more understand with the help of an example so let’s get started.

Example:

In this example, we use the updateMany() operation that uses the $unset operator to remove the document fields.

The following documents were inserted into the sales collection

db.sales.insertMany([
{"_id": 1, "item": "abc", "price": NumberDecimal("10"), "quantity": 2, "date": ISODate("2014-03-01T08:00:00Z")},
{"_id": 2, "item": "jkl", "price": NumberDecimal("20"), "quantity": 1, "date": ISODate("2014-03-01T09:00:00Z")},
{"_id": 3, "item": "xyz", "price": NumberDecimal("5"), "quantity": 10, "date": ISODate("2014-03-15T09:00:00Z")},
{"_id": 4, "item": "xyz", "price": NumberDecimal("5"), "quantity": 20, "date": ISODate("2014-04-04T11:21:39.736Z")},
{"_id": 5, "item": "abc", "price": NumberDecimal("10"), "quantity": 10, "date": ISODate("2014-04-04T21:23:13.331Z")},
{"_id": 6, "item": "def", "price": NumberDecimal("7.5"), "quantity": 5, "date": ISODate("2015-06-04T05:08:13Z")},
{"_id": 7, "item": "def", "price": NumberDecimal("7.5"), "quantity": 10, "date": ISODate("2015-09-10T08:43:00Z")},
{"_id": 8, "item": "abc", "price": NumberDecimal("10"), "quantity": 5, "date": ISODate("2016-02-06T20:20:13Z")}
])

Output:

MongoDB remove fields from the document
Documents of the sales collection

Now, we apply the condition and remove the fields from the documents:

db.sales.updateMany({ },{$unset:{ quality: " ", quantity: " "}})

Here, we used the updateMany() method and set the $unset operator to remove the two fields quality and quantity from the documents.

Remember that, If the field does not exist in the documents then $unset does nothing.

MongoDB remove fields from the document example
MongoDB remove fields from the document

We successfully removed the quantity field from all the documents and there is no field related to quality so the $unset operator does nothing.

Read: MongoDB Auto Increment ID

MongoDB remove a field from the documents matching query

In this topic, we will remove a field from the documents that match the query with help of an example.

Example:

The following documents were inserted into the person collection:

db.person.insertMany([
{"Name" : "David", "Age" : 22, "Gender" : "Male" },
{"Name" : "Mary", "Age" : 22, "Gender" : "Female" },
{"Name" : "Peter", "Age" : 24, "Gender" : "Male" },
{"Name" : "Linda", "Age" : 23, "Gender" : "Female" }
])

Next, we will apply the matching query and remove fields from the documents.

db.person.updateMany( { }, { $unset: { "Age": " ", "Class": " "}} )

Here, we used the updateMany() method and set the $unset operator to remove the two fields Age and Class from the documents.

Always do remember, the $unset first matches the fields with the documents and If any of the fields do not exist in the documents then $unset does nothing.

MongoDB remove a field from the document matching query
MongoDB remove a field from the document matching query

We successfully removed the Age field from all the documents by matching query and there is no field related to Class so the $unset operator does nothing.

Read: Missing before statement MongoDB

Remove a field from the documents using MongoDB compass

In MongoDB Compass, we can edit or remove a field from the documents in the List or Table view.

Note that, modifying documents is not permitted in MongoDB Compass Readonly Edition.

To remove a field from the documents in MongoDB Compass you have to follow the below steps:

  • Open the MongoDB Compass
  • Select the database and collection in which you want to remove the document fields
  • Select the view tab based on whether you want to view your documents in List, JSON, or Table view:
MongoDB Compass remove a field from the documents
Select the View tab to view the documents
  • To modify or remove a document field, hover over the document and click on the pencil icon
MongoDB compass remove field from the document
Click on Edit Document
  • After clicking on the pencil icon, the document enters into edit mode.
  • Here, we can perform many tasks as delete or remove the field, add a new field, and modify an existing field.
  • So to remove or delete a field of the document click the X icon to the left of the field:
MongoDB remove a field from the documents
Select the field to delete or remove
  • Once you selected the marked field then it appears in red colour
  • Here we are removing the instock field from the documents.
  • After finish the editing, Click on the UPDATE button and the field will be removed or deleted from the documents.
Remove a field from the documents using MongoDB compass
MongoDB remove a field from the documents
  • To exit or edit mode and cancel all unfinished changes to the document click on the CANCEL button.

We successfully removed the field from the documents using MongoDB Compass.

Read: MongoDB two-phase commit

MongoDB remove a field from one document

In MongoDB, we can also remove a field from one document from the collection. Let’s understand with the help of an example.

Example:

The following documents were inserted into the detail collection:

db.detail.insertMany([
{"Manufacturer":"Honda", "Model":"City", "Color":"Black"},
{"Manufacturer":"Tata", "Model":"Altroz", "Color":"Golden"},
{"Manufacturer":"Honda", "Model":"Civic", "Color":"Red"},
{"Manufacturer":"Hyundai", "Model":"i20", "Color":"white"},
{"Manufacturer":"Maruti", "Model":"Swift", "Color":"Blue"}
])

Output:

MongoDB remove a field from one document
Insert the documents into the collection

After inserting the documents into the collection, we apply a query and remove a field from a document.

db.detail.update( { "Color": "white" }, { $unset: { "Model": " " }} )

Here, the update() method is used to update one document. And, the $unset operation is used to remove the field.

In the update method, we write the query in this manner where the Color is white $unset will remove the Model field.

MongoDB remove a field from one document example
MongoDB remove a field from one document

We successfully removed the Model field where the Color is white. Here, the find() method is used to retrieve all the documents of the collection.

Read: MongoDB shutting down with code 48

MongoDB remove a field from all documents

Sometimes as per the question demand, we have to remove a particular field from all the documents. We can remove a particular field from all documents by using the updateMany() method.

And, define the field name by using the $unset operator that will help us to remove the field from all the documents.

Let’s more understand with the help of an example.

Example:

The following documents were inserted into the example collection:

db.example.insertMany([
{ "_id": 1, "name": "John", "age": 21, "address": "Highway 37, Canada"},
{ "_id": 2, "name": "Peter", "age": 23, "address": "Lowstreet 27,USA"},
{ "_id": 3, "name": "Amy", "age": 22, "address": "Apple st 652, UK"},
{ "_id": 4, "name": "Hannah", "age": 26, "address": "Mountain 21, Canada"},
{ "_id": 5, "name": "Michael", "age": 24, "address": "Valley 345, Australia"}
])

After inserting the documents into the collection, Let’s remove the age field from all the documents using the following query:

db.example.updateMany( 
{ },
 { $unset: { "age": " " }}
 )

Here, we used the updateMany() method to apply the condition to all the documents of the collection. The $unset operator is used to remove the age field from all the documents.

MongoDB remove a field from all document
MongoDB remove a field from all document

We successfully removed a field from all the documents of the collection.

Read: MongoDB find multiple conditions

Remove a field from the documents using python

In this topic, we will learn to remove a field from the documents of MongoDB using python. The update() method is used in python to modify the existing document.

And, we have to define the parameters in this method. The $unset is used to remove a field from the documents.

Now, we more understand with the help of an example:

Example:

The following documents were inserted into the data collection:

db.data.insertMany([
{"_id": 1, "name": "Smith", "class": 11, "subject": "Science/Maths"},
{"_id": 2, "name": "Tom", "class": 12, "subject": "Commerce"},
{"_id": 3, "name": "Adam", "class": 12, "Branch": "Commerce/Maths"},
{"_id": 4, "name": "Bob", "class": 11, "subject": "Arts"}
])

Now, we remove the class field where _id is 2 using python. The following script is used to remove a field:

from pymongo import MongoClient
# Create a pymongo client 
client = MongoClient('localhost', 27017) 
    
# database instance 
db = client['mydatabase'] 
    
# collection instance 
doc = db['data'] 
  
# Remove a single field from the documents
res = doc.update( { "_id": 2 }, { "$unset": { "class": " " }} )
print(res)

Here, we import the pymongo library that is used to communicate MongoDB server. And, used the MongoClient class that enables to make the successful MongoDB server connection.

After that access the database and collection, mydatabase, and data respectively. The update method uses the $unset operator to remove the class field where “_id: 2″ document.

Remove a field from the documents using python
Remove a field from the documents using python

After executing this python code, this will generate the following output:

{'n': 1, 'nModified': 1, 'ok': 1.0, 'updatedExisting': True}

This “nModified: 1” tells that one document is successfully modified from the collection.

Now, you can check the documents of the collection that it is updated or not by using the following code:

from pymongo import MongoClient
# Create a pymongo client 
client = MongoClient('localhost', 27017) 
    
# database instance 
db = client['mydatabase'] 
    
# collection instance 
doc = db['data'] 
  
# Retrieve all the document of the collection
for remove_doc in doc.find():
    print(remove_doc)

Here, The find() method is used to return all the documents of the collection. The code will retrieve all the documents of the data collection:

MongoDb remove a field from the documents using python
MongoDB remove a field from the documents using python

We Successfully removed a field from the document using python.

You may also like to read the following tutorials.

So, in this tutorial, we have discussed “MongoDB remove a field from the document. And we have also covered the following topics.

  • How to remove a field from the documents in MongoDB
  • MongoDB remove fields from the document
  • MongoDB remove a field from the documents matching query
  • Remove a field from the documents using MongoDB compass
  • MongoDB remove a field from one document
  • MongoDB remove a field from all documents
  • Remove a field from the documents using python