MongoDB : Update Modifier semantics of “$unset”

风流意气都作罢 提交于 2019-11-30 15:55:11

问题


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?


回答1:


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}});


来源:https://stackoverflow.com/questions/6327893/mongodb-update-modifier-semantics-of-unset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!