簡體   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