1

I have the following 'SaleOrderCol' collection:

{
  _id: ObjectId('1000'),
  products: [
              { _id: ObjectId('1001'), name: 'ProdA', qty: 5},
              { _id: ObjectId('1002'), name: 'ProdB', qty: 10}
            ]
},
{
  _id: ObjectId('2000'),
  products: [
              { _id: ObjectId('2001'), name: 'ProdA', qty: 5},
              { _id: ObjectId('2002'), name: 'ProdC', qty: 10}
            ]
}

I want to do an upsert to change name and qty of subdocument (1002) and try below:

SaleOrderCol.updateOne(
    { 
      "_id": ObjectId('1000'),
      "products._id": ObjectId('1002')
    },
    {
      $set : { "products": { name: 'ProdBB', qty: 15 }
    },
    { upsert: true }
)

It throws error. How to get it to work? Thank you

elvin
  • 55
  • 7
  • Please post the error message. – Mani Mar 05 '19 at 17:39
  • I realised that my question above is oversimplify to become a duplicate (as indicated by Neil Lunn). In my actual case, I actually have a subdocument resided within a subarray. However, with similar positional operator $ hint, I am able to resolve. So will close this. Thank you – elvin Mar 06 '19 at 11:25

1 Answers1

1

Use the $ positional operator

For example:

updateOne({ 
      "_id": ObjectId('1000'),
      "products._id": ObjectId('1002')
    },{
       $set: {"products.$.name": 'ProdBB' } // include other fields here
   });
);
jakemingolla
  • 1,613
  • 1
  • 10
  • 13