我在mongodb文档中具有以下结构
注意: Mongodb 3.4版
{
"_id" : "1",
"settings" : {
"shapes":[
{
"shape":"square",
"color":"blue"
},
{
"shape":"circle",
"color":"red"
},
{
"shape":"round",
"color":"black"
}
]
}
}
在这里,我想更新形状square & round
,因为value
数组具有这两种形状。在我尝试过的代码下面,但未达到我的预期。
我的代码
var value= [
{
"shape":"square",
"color":"yellow"
},
{
"shape":"round",
"color":"blue"
}
]
db.Colleges.update({"_id" : "1"},{
$set : {
"settings.shapes": value
}
},{multi:true})
更新后,我需要此输出
{
"_id" : "1",
"shapes":[
{
"shape":"square",
"color":"yellow"
},
{
"shape":"circle",
"color":"red"
},
{
"shape":"round",
"color":"blue"
}
]
}
我正在得到输出
{
"_id" : "1",
"shapes":[
{
"shape":"square",
"color":"yellow"
},
{
"shape":"round",
"color":"blue"
}
]
}
实际上,这里的圆圈和红色逐渐消失,请任何人更新我的代码。
var value
数组不是静态数组,它是动态的,基于我们要更新文档的对象。
答案 0 :(得分:0)
由于您低于MongoDB 3.6,因此无法使用arrayFilters功能。因此,您必须获取文档,用JavaScript代码修改settings.shape
,然后更新整个文档:
let doc = await db.col.findOne({_id: "1"});
let value= [
{
"shape":"square",
"color":"yellow"
},
{
"shape":"round",
"color":"blue"
}
];
value.forEach(val => {
let current = doc.settings.shapes.find(sh => sh.shape === val.shape);
if(current) {
current.color = val.color;
} else {
doc.settings.shapes.push(val);
}
});
await db.col.update({_id: "1"}, doc);