我有一个文件:
{ 'profile_set' :
[
{ 'name' : 'nick', 'options' : 0 },
{ 'name' : 'joe', 'options' : 2 },
{ 'name' : 'burt', 'options' : 1 }
]
}
如果我想add新对象profile_set
only if the name
对象的尚未被占用,无论options
,我可以限定我的update
带有一个查询对象,如果name
已经存在于profile_set
。在外壳中:
db.coll.update(
{_id: id, 'profile_set.name': {$ne: 'nick'}},
{$push: {profile_set: {'name': 'nick', 'options': 2}}})
所以这只会执行$push
对于具有匹配的文档_id
以及没有的地方profile_set
元素其中name
is 'nick'
.
Question但如果我以后需要更改尼克的名字(也许还有他的选择......),那就是change现有的数组对象,而不是添加新的。有没有一种方法可以在一个原子更新操作中做到这一点,并且仍然遵守以下唯一约束name
?
我认为有两个条件:
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
}
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)