title: Return MongoDB documents that don't contain specific inner array items
body: <p>How can I return a set of documents, each not containing a specific item in an inner array?</p>
  
  <p>My data scheme is:</p>
  
  <p>Posts:</p>
  
  <pre><code>{ 
      "_id" : ObjectId("57f91ec96241783dac1e16fe"), 
      "votedBy" : [
          {
              "userId" : "101",
              "vote": 1
          }, 
          {
              "userId" : "202",
              "vote": 2
          }
      ], 
      "__v" : NumberInt(0)
  }
  </code></pre>
  
  <p>I want to return a set of posts, non of which contain a given userId in any of the votedBy array items.
  The official documentation implies that this is possible:</p>
  
  <p><a href="https://docs.mongodb.com/manual/tutorial/query-documents/#match-a-field-without-specifying-array-index" rel="nofollow noreferrer">MongoDB documentation: Field with no specific array index</a></p>
  
  <p>Though it returns an empty set (for the more simple case of finding a document with a specific array item).
  It seems like I have to know the index for a correct set of results, like:
  votedBy.0.userId.</p>
  
  <p><a href="https://stackoverflow.com/questions/16221599/find-documents-with-arrays-not-containing-a-document-with-a-particular-field-val">This</a> Question is the closest I found, with this solution (Applied on my scheme):</p>
  
  <pre><code>db.collection.find({"votedBy": { $not: {$elemMatch: {userId: 101 } } } })
  </code></pre>
  
  <p>It works fine if the only inner document in the array matches the one I wish not to return, but in the example case I specified above, the document returns, because it finds the userId=202 inner document.</p>
  
  <p>Just to clarify: I want to return all the documents, that NONE of their votedBy array items have the given userId.</p>
  
  <p>I also tried a simpler array, containing only the userId's as an array of Strings, but still, each of them receives an Id and the search process is just the same.</p>
  
  <p>Another solution I tried is using a different collection for uservotes, and applying a lookup to perform a SQL-similar join, but it seems like there is an easier way.</p>
  
  <p>I am using mongoose (node.js).</p>