title: MongoDB: multiple $elemMatch
body: <p>I have MongoDB documents structured like this:</p>
  
  <pre><code>{_id: ObjectId("53d760721423030c7e14266f"),
  fruit: 'apple',
  vitamins: [
      {
       _id: 1,
       name: 'B7',
       usefulness: 'useful',
       state: 'free',
      }
      {
       _id: 2,
       name: 'A1',
       usefulness: 'useful',
       state: 'free',
      }
      {
       _id: 3,
       name: 'A1',
       usefulness: 'useful',
       state: 'non_free',
      }
    ]
  }
  {_id: ObjectId("53d760721423030c7e142670"),
  fruit: 'grape',
  vitamins: [
      {
       _id: 4,
       name: 'B6',
       usefulness: 'useful',
       state: 'free',
      }
      {
       _id: 5,
       name: 'A1',
       usefulness: 'useful',
       state: 'non_free',
      }
      {
       _id: 6,
       name: 'Q5',
       usefulness: 'non_useful',
       state: 'non_free',
      }
    ]
  }
  </code></pre>
  
  <p>I want to query and get all the fruits which have both <code>{name: 'A1', state: 'non_free'}</code> and <code>{name: 'B7', state: 'free'}</code>.
  In the worst case I want at least to count these entries if getting them is not possible and  if the equivalent code exists for pymongo, to know how to write it.</p>
  
  <p>For the given example I want to retrieve only the apple (first) document.</p>
  
  <p>If I use <code>$elemMatch</code> it works only for one condition, but not for both. E.g. if I query <code>find({'vitamins': {'$elemMatch': {'name': 'A1', 'state': 'non_free'}, '$elemMatch': {'name': 'B7', 'state': 'free'}}})</code> it will retrieve all the fruits with <code>{'name': 'B7', 'state': 'free'}</code>.</p>