MongoDB:更新“$unset”的修饰符语义
在 MongoDB 中,更新修饰符 unset 的工作方式如下:
考虑一个带有集合 users 的 Mongo DB 数据库 db。用户包含以下格式的文档:
//Document for a user with username: joe
{
"_id" : ObjectId("4df5b9cf9f9a92b1584fff16"),
"relationships" : {
"enemies" : 2,
"friends" : 33,
"terminated" : "many"
},
"username" : "joe"
}
如果我想删除终止的键,我必须指定 $unset 更新修饰符,如下所示:
>db.users.update({"username":"joe"},{"$unset":{"relationships.terminated": "many"}});
我的问题是,为什么我必须指定 < strong>整个键值对使$unset起作用,而不是简单地指定:
>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”替换?为什么不提供这样的功能呢?提供此类支持是否存在任何陷阱?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
简短的回答是因为
{"relationships.termerated"}
不是有效的 json/bson 对象。一个 JSON 对象由一个键和一个值组成,而{"relationships.termerated"}
只有一个键(或值,取决于你如何看待它)。幸运的是,要取消设置 Mongo 中的字段,您不需要设置要删除的字段的实际值。无论
relationships.termination
的实际值是什么,您都可以使用任何值(Mongo 文档中通常使用 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
: