您可以在Mongo中为$ addToSet指定密钥吗? [英] Can you specify a key for $addToSet in Mongo?
问题描述
我有一个文件:
{ 'profile_set' :
[
{ 'name' : 'nick', 'options' : 0 },
{ 'name' : 'joe', 'options' : 2 },
{ 'name' : 'burt', 'options' : 1 }
]
}
,并希望将新文档添加到profile_set集中(无论该名称如何)(不考虑该选项).
and would like to add a new document to the profile_set set if the name doesn't already exist (regardless of the option).
因此在此示例中,如果我尝试添加:
So in this example if I tried to add:
{'name' : 'matt', 'options' : 0}
它应该添加它,但是添加
it should add it, but adding
{'name' : 'nick', 'options' : 2}
不应执行任何操作,因为即使option
是不同的,也已经存在名称为nick
的文档.
should do nothing because a document already exists with name nick
even though the option
is different.
Mongo似乎与整个元素匹配,我最终检查它是否相同,最后我得到
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
profile_set containing [{'name' : 'nick', 'options' : 0}, {'name' : 'nick', 'options' : 2}]
是否可以通过$ addToSet来执行此操作,还是必须推送另一个命令?
Is there a way to do this with $addToSet or do I have to push another command?
推荐答案
如果profile_set
中已经存在name
,则可以使用阻止更新的查询对象来限定update
.在外壳中:
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:
db.coll.update(
{_id: id, 'profile_set.name': {$ne: 'nick'}},
{$push: {profile_set: {'name': 'nick', 'options': 2}}})
因此,这只会对具有匹配的_id
且没有profile_set
元素且name
是'nick'
的文档执行$push
.
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'
.
这篇关于您可以在Mongo中为$ addToSet指定密钥吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!