繁体   English   中英

当 mongodb 文档中的键可变时更新嵌套对象

[英]Update nested objects when key is variable in 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:

const updateFunction = async (name , variable , model)=>{
    const update = await db.collection("collection").updateOne(
        {name : name} , 
        {$set : { `car.${variable}` : {model : model } } }
      );
    }
}

updateFunction("sam" , "brand" , 321);

但它不正确并且有语法错误,那么如何更新 object 并将另一个键和值作为变量添加到它并像这样更新文档?

{
    _id :ObjectId("719le05cs456ec79b78dc0c4")
    name : "sam",
    car: {
        colors: {
            red: 10
        },
        brand : {
            model : 321
        }
    },
}

使用"car.brand"而不是'car.${brand}'

db.collection.update({
  name: "sam"
},
{
  $set: {
    "car.brand": {
      benz: 321
    }
  }
})

mongoplayground

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM