And*_*man 4 mongodb mongodb-query
我有一份文件:
{ 'profile_set' :
[
{ 'name' : 'nick', 'options' : 0 },
{ 'name' : 'joe', 'options' : 2 },
{ 'name' : 'burt', 'options' : 1 }
]
}
Run Code Online (Sandbox Code Playgroud)
如果我想将新对象添加到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}}})
Run Code Online (Sandbox Code Playgroud)
因此,这将只执行$push与匹配一个文档_id和那里没有一个profile_set地方元素name是'nick'.
问题但是如果我以后需要更改Nick的名字(也许他的选项也是......),那就是更改现有的数组对象,而不是添加新的数组对象.有没有办法在一个仍然遵循唯一约束的原子更新操作中做到这一点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
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1441 次 |
| 最近记录: |