[英]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.