mongodb 你能在 Mongo 中为 $addToSet 指定一个键吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14527980/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can you specify a key for $addToSet in Mongo?
提问by nickponline
I have a document:
我有一个文件:
{ 'profile_set' :
[
{ 'name' : 'nick', 'options' : 0 },
{ 'name' : 'joe', 'options' : 2 },
{ 'name' : 'burt', 'options' : 1 }
]
}
and would like to add a new document to the profile_set set if the name doesn't already exist (regardless of the option).
如果名称不存在(无论选项如何),并希望将新文档添加到 profile_set 集。
So in this example if I tried to add:
所以在这个例子中,如果我尝试添加:
{'name' : 'matt', 'options' : 0}
{'name' : 'matt', 'options' : 0}
it should add it, but adding
它应该添加它,但添加
{'name' : 'nick', 'options' : 2}
{'name' : 'nick', 'options' : 2}
should do nothing because a document already exists with name nick
even though the option
is different.
不应执行任何操作,因为nick
即使名称option
不同,文档也已存在。
Mongo seems to match against the whole element and I end up with to check if it's the same and I end up with
Mongo 似乎与整个元素匹配,我最终检查它是否相同,我最终得到
profile_set containing [{'name' : 'nick', 'options' : 0}, {'name' : 'nick', 'options' : 2}]
Is there a way to do this with $addToSet or do I have to push another command?
有没有办法用 $addToSet 来做到这一点,还是我必须推送另一个命令?
回答by JohnnyHK
You can qualify your update
with a query object that prevents the update if the name
is already present in profile_set
. In the shell:
您可以限定您update
有防止更新,如果一个查询对象name
是已经存在profile_set
。在外壳中:
db.coll.update(
{_id: id, 'profile_set.name': {$ne: 'nick'}},
{$push: {profile_set: {'name': 'nick', 'options': 2}}})
So this will only perform the $push
for a doc with a matching _id
and where there isn't a profile_set
element where name
is 'nick'
.
因此,这只会$push
为具有匹配项_id
且没有profile_set
元素 where name
is的文档执行'nick'
。