title: MongoDB $elemMatch $in
body: <p>So, I have a database with a load of arrays in documents in it.
  I want to find entire documents where my queries are an exact match for one or more array elements using <code>$in</code>.</p>
  
  <p>So, document structure:</p>
  
  <pre><code>{
    "_id": "76561198045636214",
    "timecreated": 1311148549,
    "unusual": [
      {
        "id": 1960169991,
        "original_id": 698672623,
        "defindex": 313,
        "_particleEffect": 19
      },
      {
        "id": 965349033,
        "original_id": 931933064,
        "defindex": 363,
        "_particleEffect": 6
      }
    ]
  }
  </code></pre>
  
  <p>I have a lot of documents like this, I want to find where a document has an array containing both a defindex 313 and a _particleEffect 19 in one array entry which means I'd have to use <code>$elemMatch</code>.</p>
  
  <p>I also want to be able to search for many different array combinations at once so for example an array with a defindex of 363 and a _particleEffect of either 19 or 6 which means I have to use <code>$in</code>.</p>
  
  <p>However, when I try to put $elemMatch and <code>$in</code> in a query, elemMatch will have nothing to do with it since it won't work on an array. I haven't been able to do it.</p>
  
  <p>My attempts so far:</p>
  
  <pre><code>{unusual:{$all:[{"defindex":{"$in":[361,378]}},{"_particleEffect":{"$in":[30,0]}}]}}
  </code></pre>
  
  <p>(my latest attempt, simply does not work.)</p>
  
  <pre><code>{"$and":[{"unusual.defindex":{"$in":[361,378]}},{"unusual._particleEffect":{"$in":[[30,36]]}}]}
  </code></pre>
  
  <p>and many more where I tried loads of combinations with <code>$elemmatch</code> and <code>$and</code>.</p>
  
  <p>(finds items in the unusual array but ignores array delimitation IE it will return a document where multiple items will be used to satisfy the condition (so at least one item with a defindex that matches and one item that has the effect.))</p>
  
  <p>I've spend a day and a half on this and have come really far, even finding a question which was almost the same as mine but was missing any mention of an <code>$in</code> part. -> <a href="https://stackoverflow.com/questions/15364920/mongodb-match-multiple-array-elements">MongoDB: Match multiple array elements</a></p>
  
  <blockquote>
    <p><strong>tl;dr:</strong> is there a way to effectively do <code>$in</code> + <code>$elemMatch</code>?</p>
  </blockquote>
  
  <p>Thanks for reading and being able to read my somewhat badly formatted post, thanks.</p>