title: Mongoose query to increment a field in an array of items if it exists otherwise add it to the document(having a hard time wording this title)
body: <p>I am having hard time wording this question which may be why I am not finding a solution already posted.</p>
  <p>I am querying a mongoDB collection using mongoose and NodeJS.</p>
  <p>The structure of the lists collection I am querying looks like this:</p>
  <pre><code>
      _id: ObjectId(&quot;1&quot;),
      listName: &quot;List 1&quot;,
      items: [
          {
             productId: ObjectId(&quot;11&quot;),
             quantity: 2
          }
      ]
  
      _id: ObjectId(&quot;2&quot;),
      listName: &quot;List 2&quot;,
      items: [
          {
             productId: ObjectId(&quot;22&quot;),
             quantity: 4
          }
      ]
  
  
  </code></pre>
  <p>I want to query the lists collection with an array of list ids. The query also contains a productInfo field like so:</p>
  <pre><code>   listIdsToQuery: [ObjectId(&quot;1&quot;), ObjectId(&quot;2)],
     productInfo: {
         productId: ObjectId(&quot;11&quot;),
         quantity: 2
     }
  
  </code></pre>
  <p>If the productId is not already in one of the lists then I just add the product to the items array.  This is the easy part and I have that down.</p>
  <p>Where I am stuck is if the product is already in the list then I just want to increment the current quantity of the product with quantity I am passing along.</p>
  <p>So with the example above:</p>
  <ul>
  <li><p>List 1 already has the product in the items array so I increment that quantity by 2</p>
  </li>
  <li><p>List 2 does not already have the product in the items array so it would just get pushed into the items array.</p>
  <p>Outcome would look like this:</p>
  </li>
  </ul>
  <pre><code>
      _id: ObjectId(&quot;1&quot;),
      listName: &quot;List 1&quot;,
      items: [
          {
             productId: ObjectId(&quot;11&quot;),
             quantity: 4
          }
      ]
  
      _id: ObjectId(&quot;2&quot;),
      listName: &quot;List 2&quot;,
      items: [
          {
             productId: ObjectId(&quot;22&quot;),
             quantity: 4
          },
          {
             productId: ObjectId(&quot;22&quot;),
             quantity: 4
          }
      ]
  </code></pre>
  <p>I hope this makes sense.  Like I said I am having a hard time coming up with a good google search wording.</p>
  <p><strong>edit:</strong>
  Right now I am thinking that my next option is to find the list by id, mutate them and then push the update to the collection on the backend.  Does this seem like an efficient viable option?</p>