I have an array subdocument called inventory which has fields like outlet and quantity. I want to update the element quantity field by matching the outlet Id, the document looks like this:
My query is like this, find the product and update inventory subdocument element quantity field which outlet id is equal to some id if there is no element matching the outlet id in the array insert one.
await Product.updateOne(
{ _id: '5f3bf38022de6f12a3771892' },
{
$set: {
'inventory.$[elem].quantity': 66,
'inventory.$[elem].outlet': '5f3bf37f22de6f12a377139b',
},
},
{
arrayFilters: [{ 'elem.outlet': '5f3bf37f22de6f12a377139b' }],
upsert: true,
},
).exec()
It updates the element array if one of the elements in the array matches the condition but, if there is no element with outlet id the upsert part is not working.