Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB : Update Modifier semantics of "$unset"

In MongoDB, the update modifier unset works as follows:

Consider a Mongo DB Database db with a collection users. Users contain a Document, of the following format:

//Document for a user with username: joe
{
    "_id" : ObjectId("4df5b9cf9f9a92b1584fff16"),
    "relationships" : {
            "enemies" : 2,
            "friends" : 33,
            "terminated" : "many"
    },
    "username" : "joe"
}

If I want to remove the terminated key, I have to specify the $unset update modifier as follows:

>db.users.update({"username":"joe"},{"$unset":{"relationships.terminated": "many"}});

My Question is, why do I have to specify the ENTIRE KEY VALUE PAIR for the $unset to work, instead of simply specifying:

>db.users.update({"username":"joe"},{"$unset":{"relationships.terminated"}});

Mon Jun 13 13:25:57 SyntaxError: missing : after property id (shell):1

Why not?

EDIT:

If the way to $unset is to specify the entire key value pair, in accordance with JSON specifications, or to add "1" as the value to the statement, why can't the Shell do the "1" substitution itself? Why isn't such a feature provided? Are there any pitfalls of providing such support?

like image 758
brud Avatar asked Jun 13 '11 07:06

brud


1 Answers

The short answer is because {"relationships.terminated"} is not a valid json/bson object. A JSON object is composed of a key and a value, and {"relationships.terminated"} only has a key (or value, depends on how you look it).

Affortunately to unset a field in Mongo you do not need to set the actual value of the field you want to remove. You can use any value (1 is commonly used in Mongo docs) no matter the actual value of relationships.terminated:

db.users.update({"username":"joe"},{"$unset":{"relationships.terminated" : 1}});
like image 55
Javier Ferrero Avatar answered Sep 20 '22 09:09

Javier Ferrero