Search code examples
mongodbunset

Mongodb: Unset Field from Document?


{
 "_id" : ObjectId("55d6cb28725f3019a5241781"),
    {
        "description" : "details of student",
        "displayGroup" : "",
        "role" : [
            {
                "name" : "admin",
                "edit" : "no"
            }
        ],
        "timestamp" : "2015-09-01 15:29:09"
    },
"subject" : {
        "class" : "Fifth",
        "description" : "5th class",
        "displayGroup" : "section A",
        "timestamp" : "2015-09-01 15:29:09"
    }
    }

This data i have,And i want to remove Subjet Array from my document where Class =5How can i remove?

i run this below Query:-

db.collectionName.update({"subject.class":"Fifth"},{$unset:{subject:""}})

But this is giving 1 Match no modification. i want to remove this from my document in one shot.Help me out?


Solution

  • Assuming you have the following document (had to add person attribute because it was not valid).

    > db.coll.findOne({"subject.class": "Fifth"})
    {
        "_id" : ObjectId("55d6cb28725f3019a5241781"),
        "person" : {
            "description" : "details of student",
            "displayGroup" : "",
            "role" : [
                {
                    "name" : "admin",
                    "edit" : "no"
                }
            ],
            "timestamp" : "2015-09-01 15:29:09"
        },
        "subject" : {
            "class" : "Fifth",
            "description" : "5th class",
            "displayGroup" : "section A",
            "timestamp" : "2015-09-01 15:29:09"
        }
    }
    

    When you use $unset on subject the document is matched and modified. Using update's multi option you can instruct mongo to update all the documents that match the query.

    > db.coll.update({"subject.class": "Fifth"}, {$unset: {subject: ""}}, {multi: true})
    WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
    

    Given subject was removed querying on subject.class is no longer possible.

    Querying by _id you can see that the field was removed from the document.

    > db.coll.findOne({_id: ObjectId("55d6cb28725f3019a5241781")})
    {
        "_id" : ObjectId("55d6cb28725f3019a5241781"),
        "person" : {
            "description" : "details of student",
            "displayGroup" : "",
            "role" : [
                {
                    "name" : "admin",
                    "edit" : "no"
                }
            ],
            "timestamp" : "2015-09-01 15:29:09"
        }
    }