0

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:

enter image description here

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.

user2620132
  • 155
  • 1
  • 1
  • 10
  • Add mongo shell code to insert documents that behave correctly and behave incorrectly to the question, and add some punctuation so that your question is readable. – D. SM Aug 19 '20 at 20:28
  • You can not apply upsert with arrayFilters, check [this](https://stackoverflow.com/questions/13588342/can-mongo-upsert-array-data) question, might be you will get some help. – turivishal Aug 20 '20 at 07:16

0 Answers0