我发现很多关于使用$elemMatch
,$set
,$in
等更新MongoDB(3.4)文档的帖子。但我需要的是更新所有{{1} }此嵌套单个文档中的animal_rules
为type
。
any_rule2
我尝试了{
"_id": "id_1",
"animals": {
"a_random_very_long_id1": {
"animal_actions": [{
"type": "any_action1",
"additional_things": [
"90000201"
]
}],
"animal_rules": [{
"type": "any_rule1",
"unrelated_field": 15
}, {
"type": "any_rule2",
"important_value": 60
}],
"_id": "a_random_very_long_id1"
},
"a_random_very_long_id2": {
"animal_actions": [{
"type": "any_action2",
"additional_things": [
"10567808"
]
}],
"animal_rules": [{
"type": "any_rule2",
"important_value": 50
},
{
"type": "any_rule3",
"other_unrelated_field": {
"type": "xx"
}
}
],
"_id": "a_random_very_long_id2"
}
}
}
之类的内容,但我甚至无法获取结果。
答案 0 :(得分:0)
我找不到任何单行程来完成这项任务,最后我想出了这个Javascript函数:
var x = db.general.findOne({"_id" : "_id1"});
for (key in x.animals) {
rules = x.animals[key].animal_rules;
rules.forEach(function (rule) {
type = rule.type;
if (type === 'any_rule2') {
theValue = rule.important_value;
rule.from = NumberInt(theValue);
rule.to = NumberInt(theValue);
delete rule.important_value;
}
});
printjson(x);
db.general.save(x);
}
希望它能为某人服务:)