Database
[{"vendor":"Vendor 1","productsInOrder":[{"orderLimit":"4","productId":"62e8e2dfcf421fdd53e3fd4b","amount":"3"},{"orderLimit":"4","productId":"62e8e2dfcf421fdd53e3fd45","amount":"4"},],},{"vendor":"Vendor 2","productsInOrder":[]}]
Query
db.collection.aggregate([{"$match":{"vendor":"Vendor 1"}},{"$set":{"exists":{"$cond":{"if":{"$gte":[{"$size":{"$filter":{"input":"$productsInOrder","as":"products","cond":{"$and":[{"$gte":["$$products.amount","$$products.orderLimit"]},/** for this product should return* `exists: true` and that's it* {* "$eq": [* "$$products.productId",* "62e8e2dfcf421fdd53e3fd45"* ]* for this product should* increase `amount` and `$merge`* the result* {* "$eq": [* "$$products.productId",* "62e8e2dfcf421fdd53e3fd4b"* ]* }* if I were to pass an id* of product that's not in the* `productsInOrder` array* new `OrderProduct` should get* created* {* maybe add some ifnull checks* "$eq": [* "$$products.productId",* "62e8e2dfcf421fdd53e3fd42"* ]* }*/]}}}},1]},"then":true,"else":false}}}},/** ...* increase `amount` property if suitable document* exists* ...*/{"$merge":{"into":"collection",/** I need `on` to reference subdocument* that has changed*/"on":"_id","let":"variables","whenMatched":"replace",/** with `fail` I'd know that no documents matched*/"whenNotMatched":"fail"}}])