我正在嘗試更新以下行:
{
"_id": "80a7",
"title": "Is React better than Angular?",
"options": [{
"option": "Yes",
"vote": 0
}, {
"option": "No",
"vote": 0
}],
假設在 中api/vote,傳遞的值為“是”,我怎樣才能$inc通過 1 更新對 Yes 的投票?
const {id, option} = req.body;
const db = await getMongoDb();
await db.collection('polls').updateOne(
{
_id: id,
},
{
$set: {
options: ???,
},
},
);
應該是什么???換成?
uj5u.com熱心網友回復:
與arrayFilters.
await db.collection('polls').updateOne({
_id: id
},
{
$inc: {
"options.$[opt].vote": 1
}
},
{
arrayFilters: [
{
"opt.option": "Yes"
}
]
})
演示@Mongo Playground
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/525479.html
標籤:mongodb
