我有一份文件:
{ '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}}的唯一约束的原子更新操作中执行此操作?
答案 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
}
});