title: MongoDB with C# Driver: How to filter on field within nested array of objects
body: <p>I'm new to MongoDB and have been struggling with this a bit. Let's say I have a document with an id, name, and array of objects:</p>
  <pre><code>{
      &quot;_id&quot;: {
          &quot;$oid&quot;: &quot;614ba49b46727413d60b99e2&quot;
      },
      &quot;Name&quot;: 1,
      &quot;ObjectArray&quot;: [
      {
          &quot;ObjectId&quot;: {
              &quot;$oid&quot;: &quot;614ba49b46727413d60b99e3&quot;
          },
          &quot;Value&quot;: &quot;some value&quot;, 
      }, 
      {
          &quot;ObjectId&quot;: {
              &quot;$oid&quot;: &quot;614ba49b46727413d60b99e5&quot;
          },
          &quot;Value&quot;: &quot;other value&quot;,
      }
      ],
  }
  </code></pre>
  <p>I have a C# class that maps to this document and everything works in that regard.  Let's say I want to add another object to the object array only if the new object's Id doesn't already exist in the array?  I'm using C# Driver for this and have tried several things.</p>
  <p>I've tried several ideas including the following --</p>
  <pre class="lang-cs prettyprint-override"><code>var filter = FilterBuilder.Eq(x =&gt; x.Id, id) &amp; 
               FilterBuilder.Nin(x =&gt; x.ObjectArray[-1].ObjectId, new[] { newDoc.ObjectId});
  </code></pre>
  <p>This unfortunately only checks the first object in the object array.  So as asked before how do I only add a new object to an array if a condition exists all within one filter?</p>
  <p>Thanks for your time.</p>
  <p>*** Solution ***</p>
  <p>Used Elematch in conjunction with Not to do the filtering all in one.</p>
  <pre class="lang-cs prettyprint-override"><code>var filter = FilterBuilder.Eq(x =&gt; x.Id, id) &amp; 
              FilterBuilder.Not(FilterBuilder.ElemMatch(x =&gt; x.ObjectArray, 
                   Builders&lt;ObjectClass&gt;.Filter.Eq(y =&gt; y.ObjectId, newDoc.ObjectId)));
  </code></pre>