首页 文章

你能在Mongo中为$ addToSet指定一个键吗?

提问于
浏览
60

我有一份文件:

{ 'profile_set' :
  [
    { 'name' : 'nick', 'options' : 0 },
    { 'name' : 'joe',  'options' : 2 },
    { 'name' : 'burt', 'options' : 1 }
  ] 
}

如果名称尚不存在(无论选项如何),都希望将新文档添加到profile_set集 .

所以在这个例子中,如果我尝试添加:

{'name' : 'matt', 'options' : 0}

它应该添加它,但添加

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

应该什么也不做,因为文件已经存在,名称为 nick ,即使 option 不同 .

Mongo似乎与整个元素匹配,我最终检查它是否相同,我最终得到了

profile_set containing [{'name' : 'nick', 'options' : 0}, {'name' : 'nick', 'options' : 2}]

有没有办法用$ addToSet执行此操作,还是我必须推送另一个命令?

1 回答

  • 79

    如果 profile_set 中已存在 name ,则可以使用查询对象限定 update ,以阻止更新 . 在shell中:

    db.coll.update(
        {_id: id, 'profile_set.name': {$ne: 'nick'}}, 
        {$push: {profile_set: {'name': 'nick', 'options': 2}}})
    

    因此,这只会为匹配 _id 的doc执行 $push ,并且不存在 profile_set 元素,其中 name'nick' .

相关问题