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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 13:01:33  来源:igfitidea点击:

Can you specify a key for $addToSet in Mongo?

mongodbpymongo

提问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 nickeven though the optionis 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 updatewith a query object that prevents the update if the nameis 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 $pushfor a doc with a matching _idand where there isn't a profile_setelement where nameis 'nick'.

因此,这只会$push为具有匹配项_id且没有profile_set元素 where nameis的文档执行'nick'