你能在 Mongo 中为 $addToSet 指定一个键吗? [英] Can you specify a key for $addToSet in Mongo?

查看:33
本文介绍了你能在 Mongo 中为 $addToSet 指定一个键吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文件:

{ '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}

它应该添加它,但添加

{'name' : 'nick', 'options' : 2}

不应该做任何事情,因为一个名为 nick 的文档已经存在,即使 option 不同.

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?

推荐答案

如果 name 已经存在,你可以使用一个查询对象来限定你的 updateprofile_set 中.在外壳中:

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 元素的文档执行 $push代码>名称是'nick'.

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屋!

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