更改阵列中的现有对象但仍保留键唯一性

时间:2014-10-27 14:48:16

标签: mongodb mongodb-query

我有一份文件:

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

如果我想新对象添加到profile_set ,如果尚未拍摄对象的name,则无论是options,我可以使用查询对象限定我的update,如果name中已存在profile_set,则会阻止更新。在shell中:

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

因此,这只会针对匹配$push的文档执行_id,并且profile_set元素不在name 'nick' name

问题但是如果我以后需要更改Nick的名字(也许是他的选项......),那就是更改现有的数组对象,而不是添加新的一。有没有办法在一个仍然遵守{{1}}的唯一约束的原子更新操作中执行此操作?

1 个答案:

答案 0 :(得分:7)

我认为有两个条件:

var newName = "somename";
var oldName = "nick";
var newOption = 3;

// if not change the name
db.coll.update({
    _id : id,
    'profile_set.name' : oldName
}, {
    $set : {
        "profile_set.$.options" : newOption
    }
});

// if change the name
db.coll.update({
    _id : id,
    $and : [ {
        'profile_set.name' : {
            $ne : newName
        }
    }, {
        'profile_set.name' : oldName    
    } ]
}, {
    $set : {
        "profile_set.$.name" : newName,
        "profile_set.$.options" : newOption

    }
});