有人可以幫我解決更新 MongoDB 檔案中的陣列物件的方法嗎,我嘗試了幾種方法,但仍然是更新,這是我的檔案,我想更新檔案中的陣列。
{
"title": "Products",
"description": "test",
"image": "bdd8510d75f6e83ad308d5f306afccef_image.jpg",
"_created_at": "2021-06-07T20:51:08.316Z",
"ratingCount": 0,
"ratingTotal": 0,
"placeListSave": [
{
"objectId": "g70brr45pfi",
"name": "Kale",
"email": "null",
"strBrandLogo": "84de8865e3223d1ca61386355895aa04_image.jpg",
"storeNumber": "56",
"phone": "0815342119",
"createdAt": "2021-06-10T10:19:53.384Z",
"image": "ad1fb7602c2188223fd891a52373cb9d_image.jpg"
},
{
"objectId": "0qokn33p773",
"name": "Apple",
"email": null,
"strBrandLogo": null,
"storeNumber": "01",
"phone": "011 393 8600",
"createdAt": "2021-06-11T03:11:17.342Z",
"image": "8cfcbf2bcb5e3b4ea8ade44d3825bb52_image.jpg"
}
]
}
所以我只想更新蘋果物件并更改資料,我嘗試了以下代碼但似乎不起作用。
`
var db = client.db("test");
try {
db.collection("ShoppingCentres").updateOne({
"title": req.body.product,
"placeListSave.objectId": req.body.id,
}, {
$set: {
"placeListSave.$.email": req.body.email,
"placeListSave.$.storeNumber": req.body.storeNumber,
"placeListSave.$.phone": req.body.phone,
"placeListSave.name": req.body.name,
},
});
res.json("client");
} catch (e) {
console.log("verify", e);
}
});`
uj5u.com熱心網友回復:
arrayFilters 似乎適合這里:
db.collection.update({
"title": "Products",
"placeListSave.objectId": "0qokn33p773",
},
{
$set: {
"placeListSave.$[x].email": "[email protected]",
"placeListSave.$[x].storeNumber": "test",
"placeListSave.$[x].phone": "test",
"placeListSave.$[x].name": "test"
}
},
{
arrayFilters: [
{
"x.objectId": "0qokn33p773"
}
]
})
解釋:為需要更新的元素添加名為“x”的陣列過濾器和 objectId,并在 $set 階段使用此過濾器來更新必要的元素。
提示:為了加快更新,您需要在標題欄位上添加索引或在 title placeListSave.objectId 上添加復合索引
操場
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/413816.html
標籤:
上一篇:試圖弄清楚如何使用.Where將字串字符添加到字串陣列中
下一篇:未看到陣列更改(其他執行緒?)
