Update with UNSET Operator: MongoDB

Lets use $unset operator along with update() method, to update the documents.

test database, names collection

> db.names.find().pretty()
{
        "_id" : ObjectId("53c3fc2005e0ce2719d91bd2"),
        "Company" : "Google",
        "Product" : "Nexus",
        "No" : 1
}
{
        "_id" : ObjectId("53c3fd3bb9ae26fa217b1e12"),
        "Company" : "Apple",
        "Product" : "iPhone",
        "No" : 2
}

Here we have 2 documents with fields _id, Company, Product and No.

Update with UNSET Operator: MongoDB



YouTube Link: https://www.youtube.com/watch?v=8UUdITiZ5ZE [Watch the Video In Full Screen.]



We could remove a field using update() method, by not specifying it in the second argument.

> db.names.update({"No": 1}, {"Company": "Google", "No": 1});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

> db.names.find().pretty()
{
        "_id" : ObjectId("53c3fc2005e0ce2719d91bd2"),
        "Company" : "Google",
        "No" : 1
}
{
        "_id" : ObjectId("53c3fd3bb9ae26fa217b1e12"),
        "Company" : "Apple",
        "Product" : "iPhone",
        "No" : 2
}

Related Read: Update Method: MongoDB

This way, we could eliminate the field Product. But this is a tedious process – we need to remember all the fields inorder to achieve this. It gets difficult when we have many fields in our document. To solve this problem, we have $unset operator, where we only need to know the field name which we want to remove.

> db.names.update({"No": 1}, {$unset: {"Product": 1}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

> db.names.find().pretty()
{
        "_id" : ObjectId("53c3fc2005e0ce2719d91bd2"),
        "Company" : "Google",
        "No" : 1
}
{
        "_id" : ObjectId("53c3fd3bb9ae26fa217b1e12"),
        "Company" : "Apple",
        "Product" : "iPhone",
        "No" : 2
}

$unset operator syntax is same to unset or remove array from a document.

> db.names.update({"No": 1}, {$set: {"Product": ["LG", "Samsung", "HTC"]}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

> db.names.find().pretty()
{
        "_id" : ObjectId("53c3fc2005e0ce2719d91bd2"),
        "Company" : "Google",
        "No" : 1,
        "Product" : [
                "LG",
                "Samsung",
                "HTC"
        ]
}
{
        "_id" : ObjectId("53c3fd3bb9ae26fa217b1e12"),
        "Company" : "Apple",
        "Product" : "iPhone",
        "No" : 2
}

> db.names.update({"No": 1}, {$unset: {"Product": 1}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

> db.names.find().pretty()
{
        "_id" : ObjectId("53c3fc2005e0ce2719d91bd2"),
        "Company" : "Google",
        "No" : 1
}
{
        "_id" : ObjectId("53c3fd3bb9ae26fa217b1e12"),
        "Company" : "Apple",
        "Product" : "iPhone",
        "No" : 2
}

Related Read: Update with SET Operator: MongoDB