MongoDB:更新"$ unset"的修饰符语义

bru*_*rud 5 language-agnostic json mongodb unset semantics

在MongoDB中,更新修饰符unset的工作方式如下:

考虑具有集合用户的Mongo DB数据库db.用户包含以下格式的Document:

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

如果我想删除已终止的密钥,我必须指定$ unset update修饰符,如下所示:

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

我的问题是,为什么我必须为$ unset 指定整个键值对,而不是简单地指定:

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

Mon Jun 13 13:25:57 SyntaxError: missing : after property id (shell):1
Run Code Online (Sandbox Code Playgroud)

为什么不?

编辑:

如果$ unset的方法是根据JSON规范指定整个键值对,或者在语句中添加"1"作为值,为什么Shell本身不能进行"1"替换?为什么不提供这样的功能?是否存在提供此类支持的陷阱?

Jav*_*ero 25

简短的回答是因为{"relationships.terminated"}它不是有效的json/bson对象.JSON对象由键和值组成,并且{"relationships.terminated"}只有一个键(或值,取决于您的查看方式).

幸运的是,要在Mongo中取消设置字段,您不需要设置要删除的字段的实际值.无论实际值如何,您都可以使用任何值(1在Mongo文档中常用)relationships.terminated:

db.users.update({"username":"joe"},{"$unset":{"relationships.terminated" : 1}});
Run Code Online (Sandbox Code Playgroud)