简体   繁体   中英

How to update an Array of Objects field in MongoDb

I have a data structure, like so

{
  _id: '',
  name: 'A',
  financialReports: {
    monthlyBill: 20,
    monthlyBillReports: [
      {
        month: 'JAN',
        isPaid: true
      },
      {
        month: 'FEB',
        isPaid: false
      },
      {
        month: 'MAR',
        isPaid: false
      },
      {
        month: 'APR',
        isPaid: false
      },
      ...
    ]
  }
},
...

How should I dynamically update financialReports.monthlyBillReports[i].isPaid to true? I got array of data that indicate to month field in Database from front-end ['FEB', 'APR'] , But I am not sure if I could iterate over the array and make update query to Database.

you can do a loop something like:

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
          )
    })  

or in a more straight forward manner:

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
              )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM