title: MongoDB - Update multiple subdocuments in array in multiple documents
body: <p>I'm making a node.js website. I have a <code>posts</code> collection in which comments for posts are stored in an array with the comment author's details as nested object.</p>
  <p>This is new post's schema:</p>
  <pre class="lang-json prettyprint-override"><code>{
      &quot;text&quot;: text,
      &quot;image&quot;: image,
      &quot;video&quot;: video,
      &quot;type&quot;: type,
      &quot;createdAt&quot;: createdAt,
      &quot;reactions&quot;: [],
      &quot;comments&quot;: [],
      &quot;shares&quot;: [],
      &quot;user&quot;: {
          &quot;_id&quot;: user._id,
          &quot;username&quot;: user.username
      }
  }
  </code></pre>
  <p>This is new comment being pushed to its post:</p>
  <pre class="lang-js prettyprint-override"><code>$push: {
      &quot;comments&quot;: {
          &quot;_id&quot;: commentId,
          &quot;user&quot;: {
              &quot;_id&quot;: user._id,
              &quot;type&quot;: type,
              &quot;name&quot;: user.name,
              &quot;profileImage&quot;: user.photo,
          },
          &quot;comment&quot;: comment,
          &quot;createdAt&quot;: createdAt,
          &quot;replies&quot;: []
      }
  }                           
  </code></pre>
  <p>To avoid storing comments in another collection and doing complex multiple lookups(I'm doing 1 lookup to get post author details but couldn't add another to make it work for comments) to consolidate the newsfeed I decided to save comments and their author's details embedded in the posts.</p>
  <p>Now when user profile picture is updated all the comments have to be updated to show the new picture.</p>
  <p>I included this updateMany query along with the photo updation route in server.js file:</p>
  <pre class="lang-js prettyprint-override"><code>database.collection(&quot;posts&quot;).updateMany({
      &quot;comments.user._id&quot;: user._id,
      &quot;comments.user.type&quot;: &quot;friend&quot;
  }, {
      $set: {
          &quot;comments.$.user.profileImage&quot;: photo
      }
  });
  </code></pre>
  <p>The problem here is that this updates <strong>only the first</strong> matching comment in all posts.</p>
  <p>I need to update <strong>all</strong> matching comments in all posts.</p>
  <p>I'm actually just learning by doing this following youtube videos, so please help me.</p>