title: Mongodb check If field exists in an sub-document of an array
body: <p>I am trying to check If a field exists in a sub-document of an array and if it does, it will only provide those documents in the callback. But every time I log the callback document it gives me all values in my array instead of ones based on the query. </p>
  
  <p><a href="https://docs.mongodb.com/manual/reference/operator/projection/elemMatch/#zipcode-search" rel="nofollow noreferrer">I am following this tutorial</a> 
  And the only difference is I am using the <strong>findOne</strong> function instead of <strong>find</strong> function but it still gives me back all values. I tried using find and it does the same thing. </p>
  
  <p>I am also using the same collection style as the example in the link above.</p>
  
  <p><strong>Example</strong>
  <a href="https://i.stack.imgur.com/rRuNM.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rRuNM.jpg" alt="enter image description here"></a>
  In the image above you can see in the image above I have a document with a <strong>uid</strong> field and a <strong>contacts</strong> array. What I am trying to do is first select a document based on the inputted <strong>uid</strong>. Then after selecting that document then I want to display the values from the <strong>contacts</strong> array where <strong>contacts.uid</strong> field exists. So from the image above only values that would be displayed is <strong>contacts[0]</strong> and <strong>contacts[3]</strong> because <strong>contacts<a href="https://docs.mongodb.com/manual/reference/operator/projection/elemMatch/#zipcode-search" rel="nofollow noreferrer">1</a></strong>  doesn't have a uid field.</p>
  
  <pre><code>Contact.contactModel.findOne({$and: [
  
          {uid: self.uid},
  
          {contacts: {
  
            $elemMatch: {
  
              uid: {
  
                $exists: true,
  
                $ne: undefined,
  
              }
  
            }
  
          }}
  
        ]}
  </code></pre>