[英]Update nested objects when key is variable in mongodb document
I want to update car field and add more keys like colors
in this mongodb document:我想更新汽车字段并在此 mongodb 文档中添加更多键,例如
colors
:
{
_id :ObjectId("719le05cs456ec79b78dc0c4")
name : "sam",
car: {
colors: {
red: 10
}
},
}
But my problem is adding variable as key to car object, In my function the variable
argument is an object and the model is a number, I want to add this argument to the car object in document, So I update the document: But my problem is adding variable as key to car object, In my function the
variable
argument is an object and the model is a number, I want to add this argument to the car object in document, So I update the document:
const updateFunction = async (name , variable , model)=>{
const update = await db.collection("collection").updateOne(
{name : name} ,
{$set : { `car.${variable}` : {model : model } } }
);
}
}
updateFunction("sam" , "brand" , 321);
But it doesn't correct and has syntax error, So how can I update an object and add another key and value to it as an variable and update the document like this?但它不正确并且有语法错误,那么如何更新 object 并将另一个键和值作为变量添加到它并像这样更新文档?
{
_id :ObjectId("719le05cs456ec79b78dc0c4")
name : "sam",
car: {
colors: {
red: 10
},
brand : {
model : 321
}
},
}
use "car.brand"
instead of 'car.${brand}'
使用
"car.brand"
而不是'car.${brand}'
db.collection.update({
name: "sam"
},
{
$set: {
"car.brand": {
benz: 321
}
}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.