$unset Operator in MongoDB: Quick Guide

MongoDB can store huge amounts of data and sometimes while inserting data in bulk some fields that we want to remove earlier remain there and are inserted in the database with empty or some values. Deleting these fields from all documents using some ordinary method can be painful. So here comes another extremely useful MongoDB operator for that: the $unset operator, somewhat opposite to the $set operator.

In this article, we will understand the $unset operator along with its syntax and see how to use it to remove fields from MongoDB documents. Let’s get started.

MongoDB $unset Operator

The $unset operator is used to remove or delete fields from documents. We can use this operator with update operation methods like updateOne(), updateMany(), or update() to remove certain fields from the selected documents.

The syntax for using the $unset operator is quite straightforward.

Syntax:

db.collection.update(
   { <query> },
  { $unset: { field1: "", field2: "", ... } }
)

Parameters:

  1. “collection” is the collection name where we are looking for the documents.
  2. “{}” is used to specify that the operation will be performed on all documents in the collection.
  3. “update()” is the method we are using to update the documents.
  4. “fieldN” is the field will we want to remove.

We have a similar post where we also cover $unset but with Node.js to remove fields from MongoDB documents. If you are going to use this operator with Node.js click here to read to discover how. However, the core functionality is the same.

Examples of Using MongoDB $unset Operator Inside the Mongo Shell

Let us now look at some practical examples of using the $unset operator in MongoDB.

Setup:

1. Start the MongoDB shell.

2. Execute the following commands to list all the available databases & move into one of them.

show dbs
use shop

Here as an example, we are using our “shop” database which contains a collection named “shoes”.

3. Let’s pretty print the documents in the “shoes” collection to see what our sample collection looks like.

> db.shoes.find({}).pretty()
{
        "_id" : ObjectId("616b18a556e71503e4a0334d"),
        "name" : "Mariana Grider Boots",
        "price" : 23000,
        "size" : 7,
        "style" : "Slingbacks",
        "onSale" : false,
        "freeDelivery" : true,
        "__v" : 0,
        "moreDetails" : {
                "qtyAvlbl" : 40,
                "colors" : " "
        }
}
{
        "_id" : ObjectId("616b18a556e71503e4a0334e"),
        "name" : "Purple Shimmery Heels",
        "price" : 13380,
        "size" : 6,
        "style" : "Peep Toes",
        "onSale" : true,
        "freeDelivery" : false,
        "__v" : 0,
        "moreDetails" : {
                "qtyAvlbl" : 10,
                "colors" : " "
        },
        "itemNumber" : 0
}
{
        "_id" : ObjectId("616b18a556e71503e4a0334f"),
        "name" : "Zac Porter Straps",
        "price" : 19760,
        "size" : 8,
        "style" : "Ankle Strap",
        "onSale" : true,
        "freeDelivery" : true,
        "__v" : 0,
        "moreDetails" : {
                "qtyAvlbl" : 10,
                "colors" : " "
        }
}
{
        "_id" : ObjectId("616b18a556e71503e4a03350"),
        "name" : "Valerina's Red Carpet Toes",
        "price" : 26000,
        "size" : 9,
        "style" : "Scarpin",
        "onSale" : false,
        "freeDelivery" : false,
        "__v" : 0,
        "moreDetails" : {
                "qtyAvlbl" : 10,
                "colors" : " "
        }
}
{
        "_id" : ObjectId("616b18a556e71503e4a03351"),
        "name" : "Neeta Parmar's Stylish Bees 'n' Honey Boots",
        "price" : 10780,
        "size" : 7,
        "style" : "Wedge Booties",
        "onSale" : true,
        "freeDelivery" : true,
        "__v" : 0,
        "moreDetails" : {
                "qtyAvlbl" : 10,
                "colors" : " "
        }
}
{
        "_id" : ObjectId("6171bbf968378cae00d83aca"),
        "name" : "Caroline Wielder Shoes",
        "price" : NumberDecimal("14999.985"),
        "size" : 5,
        "style" : "Wedge Booties",
        "onSale" : true,
        "freeDelivery" : false,
        "moreDetails" : {
                "qtyAvlbl" : 10,
                "colors" : " "
        }
}
{
        "_id" : ObjectId("6171bbf968378cae00d83acb"),
        "name" : "Marilyn Jaworski Sky Highs",
        "price" : NumberDecimal("12399.85"),
        "size" : 5,
        "style" : "Scarpin",
        "onSale" : false,
        "freeDelivery" : false,
        "moreDetails" : {
                "qtyAvlbl" : 10,
                "colors" : " "
        }
}

Note: In the above code, we have used the pretty() function to format the query results with proper indentation and generate easily readable output. 

Using $unset Operator to Remove a Field from all Documents

Let’s say we want to remove the “freeDelivery” field from all our documents. In that case, we can make use of the $unset operator to help us out.

Query:

> db.shoes.updateMany(
...    { },
...    { $unset: { "freeDelivery" : "" } }
... )

{ "acknowledged" : true, "matchedCount" : 7, "modifiedCount" : 7 }

Output:

> db.shoes.find({}).pretty()

{
        "_id" : ObjectId("616b18a556e71503e4a0334d"),
        "name" : "Mariana Grider Boots",
        "price" : 23000,
        "size" : 7,
        "style" : "Slingbacks",
        "onSale" : false,
        "__v" : 0,
        "moreDetails" : {
                "qtyAvlbl" : 40,
                "colors" : " "
        }
}
{
        "_id" : ObjectId("616b18a556e71503e4a0334e"),
        "name" : "Purple Shimmery Heels",
        "price" : 13380,
        "size" : 6,
        "style" : "Peep Toes",
        "onSale" : true,
        "__v" : 0,
        "moreDetails" : {
                "qtyAvlbl" : 10,
                "colors" : " "
        },
        "itemNumber" : 0
}
{
        "_id" : ObjectId("616b18a556e71503e4a0334f"),
        "name" : "Zac Porter Straps",
        "price" : 19760,
        "size" : 8,
        "style" : "Ankle Strap",
        "onSale" : true,
        "__v" : 0,
        "moreDetails" : {
                "qtyAvlbl" : 10,
                "colors" : " "
        }
}
{
        "_id" : ObjectId("616b18a556e71503e4a03350"),
        "name" : "Valerina's Red Carpet Toes",
        "price" : 26000,
        "size" : 9,
        "style" : "Scarpin",
        "onSale" : false,
        "__v" : 0,
        "moreDetails" : {
                "qtyAvlbl" : 10,
                "colors" : " "
        }
}
{
        "_id" : ObjectId("616b18a556e71503e4a03351"),
        "name" : "Neeta Parmar's Stylish Bees 'n' Honey Boots",
        "price" : 10780,
        "size" : 7,
        "style" : "Wedge Booties",
        "onSale" : true,
        "__v" : 0,
        "moreDetails" : {
                "qtyAvlbl" : 10,
                "colors" : " "
        }
}
{
        "_id" : ObjectId("6171bbf968378cae00d83aca"),
        "name" : "Caroline Wielder Shoes",
        "price" : NumberDecimal("14999.985"),
        "size" : 5,
        "style" : "Wedge Booties",
        "onSale" : true,
        "moreDetails" : {
                "qtyAvlbl" : 10,
                "colors" : " "
        }
}
{
        "_id" : ObjectId("6171bbf968378cae00d83acb"),
        "name" : "Marilyn Jaworski Sky Highs",
        "price" : NumberDecimal("12399.85"),
        "size" : 5,
        "style" : "Scarpin",
        "onSale" : false,
        "moreDetails" : {
                "qtyAvlbl" : 10,
                "colors" : " "
        }
}

We have successfully removed the “freeDelivery” field from all our documents using the $unset operator.

Using $unset Operator to Remove a Field in an Embedded Document

Let’s now try to remove an embedded field. An embedded field is a field that is present or nested inside another field.

Query:

> db.shoes.updateMany(
...    { },
...    { $unset: { "moreDetails.colors" : "" } }
... )

{ "acknowledged" : true, "matchedCount" : 7, "modifiedCount" : 7 }

As you can see in the above query, we can use dot notation to match embedded elements.

Output:

> db.shoes.find({}).pretty()

{
        "_id" : ObjectId("616b18a556e71503e4a0334d"),
        "name" : "Mariana Grider Boots",
        "price" : 23000,
        "size" : 7,
        "style" : "Slingbacks",
        "onSale" : false,
        "__v" : 0,
        "moreDetails" : {
                "qtyAvlbl" : 40
        }
}
{
        "_id" : ObjectId("616b18a556e71503e4a0334e"),
        "name" : "Purple Shimmery Heels",
        "price" : 13380,
        "size" : 6,
        "style" : "Peep Toes",
        "onSale" : true,
        "__v" : 0,
        "moreDetails" : {
                "qtyAvlbl" : 10
        },
        "itemNumber" : 0
}
{
        "_id" : ObjectId("616b18a556e71503e4a0334f"),
        "name" : "Zac Porter Straps",
        "price" : 19760,
        "size" : 8,
        "style" : "Ankle Strap",
        "onSale" : true,
        "__v" : 0,
        "moreDetails" : {
                "qtyAvlbl" : 10
        }
}
{
        "_id" : ObjectId("616b18a556e71503e4a03350"),
        "name" : "Valerina's Red Carpet Toes",
        "price" : 26000,
        "size" : 9,
        "style" : "Scarpin",
        "onSale" : false,
        "__v" : 0,
        "moreDetails" : {
                "qtyAvlbl" : 10
        }
}
{
        "_id" : ObjectId("616b18a556e71503e4a03351"),
        "name" : "Neeta Parmar's Stylish Bees 'n' Honey Boots",
        "price" : 10780,
        "size" : 7,
        "style" : "Wedge Booties",
        "onSale" : true,
        "__v" : 0,
        "moreDetails" : {
                "qtyAvlbl" : 10
        }
}
{
        "_id" : ObjectId("6171bbf968378cae00d83aca"),
        "name" : "Caroline Wielder Shoes",
        "price" : NumberDecimal("14999.985"),
        "size" : 5,
        "style" : "Wedge Booties",
        "onSale" : true,
        "moreDetails" : {
                "qtyAvlbl" : 10
        }
}
{
        "_id" : ObjectId("6171bbf968378cae00d83acb"),
        "name" : "Marilyn Jaworski Sky Highs",
        "price" : NumberDecimal("12399.85"),
        "size" : 5,
        "style" : "Scarpin",
        "onSale" : false,
        "moreDetails" : {
                "qtyAvlbl" : 10
        }
}

We have successfully removed the “colors” nested document from all our documents.

Using $unset Operator to Remove a Missing or Non-Existent Field

Let’s see what happens if we pass a condition for removing a field that does not exist in the documents.

Query:

> db.shoes.updateMany(
...    { },
...    { $unset: { "isAvailable" : "" } }
... )

{ "acknowledged" : true, "matchedCount" : 7, "modifiedCount" : 0 }

The “modifiedCount” property shows a 0 value which indicates the operation was a no-op, meaning, it did not change anything.

Conclusion

$unset proved to be an essential operator when we have to remove certain fields from all or some selected documents. In this article, we have seen its syntax and learned how to use it in MongoDB shell with multiple examples. 

If you want an alternative to this, you can use the $pull operator. $pull is mainly used to remove specific elements from arrays but you can use it with an empty criteria to remove a field as well. We hope that after reading this article you will get answers to all your questions.

Read More:

Reference

$unset — MongoDB Manual

Aneesha S
Aneesha S
Articles: 171