MongoDB

How to Remove the Document Fields with $Unset in MongoDB

In MongoDB, particular fields may be eliminated from the records in a collection using the $unset keyword. It enables you to carefully delete the columns from the records that you no longer require or wish to erase. This operator is beneficial when you want to alter your data model or delete the out-of-date data from your records. This guide will be a helpful material for those who want to learn the basics of using the $unset operator.

Create a Collection

To unset the fields of collection, we should have some data in our collection. Therefore, we already created a collection entitled “Data” and added a total of five records to it. Those five records are displayed on the MongoDB shell via the “find” function query. The records contain the unique “_id” field for the records. Also, we have the string type “name” field along with the “Score” field array-type. In some records, the “score” field is null, empty, an array or string, and has no record.

test> db.Data.find({})

Example 1:

Let’s say you want an update on certain records of the “Data” collection like deleting some records. For this, you must use the $unset operator of MongoDB within the update command.

For instance, we want to unset the record of the “name” and “score” fields of the “Data” collection where the “score” field is “null”. As we need to update a single record, we should employ MongoDB’s “updateOne” function on the “Data” collection. The first argument of the “updateOne” function is used to identify the record that you want to update by specifying the unique value of one of its fields.

In our case, this unique value field is “score”, i.e. to update the record where the “score” field is “null”. The other parameter of the updateOne() function uses the $unset operator to remove the existing values of the specified field names, i.e. the empty inverted commas. In this case, we want to unset the “name” and “score” fields as displayed. The query execution returns the acknowledgement, i.e. one record is updated.

db.Data.updateOne(

  { score: null },

  { $unset: { name: "", score: "" } }

)

After the successful update of one record, we check for the “Data” collection again via the “find” method. The output displays that all the records are untouched except the one with only the unique identifier “_id” left because all the other fields are unset using MongoDB’s “unset” operator.

test> db.Data.find({})

Example 2:

We witnessed a single value field update using the “unset” operator in the previous example. But, we need to learn about unsetting the nested fields. We need to have the nested field records in our database collection for this. So, we create a “Teacher” collection and insert multiple records in it at once which also contains the nested “sub” field and the “shift” field array-type. The records are added successfully as per the output.

db.Teacher.insertMany([

{ "name" : "John", "pay" : 799, "sub" : { "math" : 4, "comp" : 9.5, "phy" : 17 },"shift":["mor","eve"]},

{ "name" : "Ana", "pay" : 899, "sub" : { "math" : 22, "comp" : 10.5, "phy" : 15 },"shift":["mor","eve", "night"]},

{ "name" : "Sam", "pay" : 899, "sub" : { "math" : 12, "comp" : 9, "phy" : 14 },"shift":["mor","eve"]},

{ "name" : "Paul", "pay" : 699, "sub" : { "math" : 18, "comp" : 8, "phy" : 12 },"shift":["mor","eve", "night"]},

{ "name" : "Zoni", "pay" : 599, "sub" : { "math" : 14, "comp" : 4, "phy" : 16 },"shift":["mor","eve"]},

])

After adding these records, we have to confirm that these records are added perfectly via the “find” function application on the “Teacher” collection. The output of this method displays all five records separately in the form of documents along with their embedded fields like name, pay, sub, and shift.

test> db.Teacher.find({})

In this illustration, we will show you how to unset an embedded field of any record from the collection. For this, we choose the record where the “name” field has the “Sam” value. The method of using the “unset” operator is the same as we used in the first illustration via the updateOne() MongoDB function.

Within the $unset operator, we specify the “pay” field to empty the inverted commas. Now, to unset the nested “sub” field, we need to specify the embedded “match” field along with the parent field using the “dot” product, i.e. “sub.match”. In this way, the embedded field is unset.

db.Teacher.updateOne(

{ name: "Sam" },

{ $unset: { pay: "", "sub.math": "" } }

)

After executing the previous query successfully, we try the “findOne()” function of MongoDB to only display the specific single record from the “Teacher” collection where the “name” is “Sam”; it is just an updated record. The output image displays the single record along with its updated fields, i.e. the “pay” field is removed after the application of “unset” and the “sub” field has no embedded “math” value anymore.

test> db.Teacher.findOne({name: "Sam"}, {})

Example 3:

After reviewing the examples of unsetting the single nested and non-nested records, we will demonstrate how to update multiple records simultaneously. Let’s say you want to update the array-type “shift” field of the “Teacher” collection for now. First, we only display the “shift” field of the “Teacher” collection. This field gets a different number of values in its array format, i.e. 2 or 3.

test> db.Teacher.find({}, {shift:1})

As the arrays store the values using the indexes, we need to utilize the index number of values for the “shift” field to unset its values. Also, to unset the “shift” field of all the collection records, we should utilize the “updateMany()” function in the “Db” command. To update all the records of the collection, there is no need to specify the condition in the first argument.

Within the second argument, we apply the “$unset” operator on the index “0” of the “shift” array field using the “dot” product, i.e. “shift.0”. The update query gets a successful execution as per the output.

db.Teacher.updateMany({}, { $unset: { "shift.0": "" } })

Let’s check for the “Teacher” collection records for only its array-type “shift” field via the “find” method as used in the following image. The output displays the index “0” of the “shift” field as “null”; unset always sets the array fields to “null” if it is left empty. This is because, in arrays, the values are stored at specific locations using indexes. Therefore, removing a value doesn’t completely remove its place. Although, you can set a new value for the field.

test> db.Teacher.find({}, {shift:1})

Conclusion

This guide discovers the different methods of utilizing the $unset operator on the database collections in MongoDB. We discussed the simplest examples of unset to remove a single independent field, nested field value, or an array value via indexes.

About the author

Saeed Raza

Hello geeks! I am here to guide you about your tech-related issues. My expertise revolves around Linux, Databases & Programming. Additionally, I am practicing law in Pakistan. Cheers to all of you.