MongoDB:"$ unset"的更新修饰符语义. [英] MongoDB : Update Modifier semantics of "$unset"

查看:140
本文介绍了MongoDB:"$ unset"的更新修饰符语义.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在MongoDB中,未设置update修饰符的工作方式如下:

In MongoDB, the update modifier unset works as follows:

考虑一个具有集合 users 的Mongo数据库数据库 db .用户包含以下格式的文档:

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"
}

如果要删除终止键,则必须指定$ unset update修饰符,如下所示:

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

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

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

为什么不呢?

编辑:

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

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?

推荐答案

简短的答案是因为{"relationships.terminated"}不是有效的json/bson对象. JSON对象由一个键和一个值组成,{"relationships.terminated"}仅包含一个键(或值,取决于您的外观).

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).

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

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

这篇关于MongoDB:"$ unset"的更新修饰符语义.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆