0

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.

  • You might consider using [`Bulk.find.arrayFilters()`](https://www.mongodb.com/docs/manual/reference/method/Bulk.find.arrayFilters/) to specify the array element you want to update. – rickhg12hs Aug 25 '22 at 00:38
  • If you know the / one specific sub-document you want to update in the array, then you can use the `$` update operator. It will update the first matching sub-document in the array. Refer array update operators: https://www.mongodb.com/docs/v6.0/reference/operator/update/#array – prasad_ Aug 25 '22 at 05:54
  • @rickhg12hs That was exactly what I was looking for. For anyone else using https://www.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 } ] } – Joe Whitehorn Aug 25 '22 at 14:45

1 Answers1

0

@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 } ] }