Home > database >  Mongo adding a field to a specific object in an array of objects using updateOne during a bulkUpdate
Mongo adding a field to a specific object in an array of objects using updateOne during a bulkUpdate

Time:08-27

Use case

Adding a field to a specific object in an array of objects using updateOne during a bulkUpdateOps

Blockers

  1. I have been unable to find a way to identify and update a specific object in the subdocument array of a specific record.
  2. I only have access to this DB through MongoDB Compass, and I plan to use the provided mongosh tool.

Data example

Our purchaseorders model looks like this:

{
   _id: uuid,
   ...rest,
   documents:[
      {
         _id:uuid,
         forignKey2:string (optional),
         keyIWantToAdd:string (optional),
         ...rest
      }
   ]
}

So if I have

{
   _id:*1,
   documents:[
      {
         _id:*2,
         forignKey2:'no-test',
         ...rest
      },
      {
         _id:*3,
         forignKey2:'test',
         ...rest
      },
   ]
}

I want to add a key and value like this (really I'm willing to do anything to set these values, this is just the closest I have been able to get):

var bulkUpdateOps = db.purchaseorders.initializeOrderedBulkOp();
bulkUpdateOps.find('*1').updateOne({
   $set:{
      documents.[index of document object with forignKey2:'test' or _id:*3 whichever is easier].keyIWantToAdd:'valueIWantToAdd'
   }
})
bulkUpdateOps.execute();

Any help or suggestions would be greatly appreciated.

CodePudding user response:

@rickhg12hs posted exactly what I was looking for. For anyone else using mongodb.com/docs/manual/reference/method/Bulk.find.arrayFilters the bulk find is being ran on an array of objects like this: { grades:[ { grade: 85, mean: number } ] }

  • Related