[英]How to update an Array of Objects field in MongoDb
我有一個數據結構,就像這樣
{
_id: '',
name: 'A',
financialReports: {
monthlyBill: 20,
monthlyBillReports: [
{
month: 'JAN',
isPaid: true
},
{
month: 'FEB',
isPaid: false
},
{
month: 'MAR',
isPaid: false
},
{
month: 'APR',
isPaid: false
},
...
]
}
},
...
我應該如何將financialReports.monthlyBillReports[i].isPaid
動態更新為 true? 我從前端['FEB', 'APR']
獲得了指示數據庫中月份字段的數據數組,但我不確定是否可以遍歷數組並對數據庫進行更新查詢。
你可以做一個循環,比如:
let yourArray = ['FEB', 'APR'] // just mocking the array
yourArray.forEach((mo)=>{
collectionName.findOneAndUpdate(
{_id: 'document id goes here'},
{ '$set': {'financialReports.monthlyBillReports.$[frFilter].isPaid': true}},
{ arrayFilters: [ {frFilter.month: mo} ], multi: true}
).then(
//do whatever you need here
)
})
或更直接的方式:
collectionName.findOneAndUpdate(
{_id: 'document id goes here'},
{ '$set': {'financialReports.monthlyBillReports.$[frFilter].isPaid': true}},
{arrayFilters: [ {frFilter.month: {$in: yourArray} } ], multi: true}
).then(
//do whatever you need here
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.