title: Aggregate Count Array Members Matching Condition
body: <p>I'm having some trouble, as stated in title, to count elements in an Array using MongoDB.
  I have a DB with only one document, made as follow:</p>
  <pre><code> {_id: ObjectId(&quot;abcdefghilmnopq&quot;),
      &quot;Array&quot;: [
        {field1: &quot;val1&quot;,
         field2: &quot;val2&quot;,
         field3: &quot;val3&quot;,
         ...
         },
         {field1: &quot;Value1&quot;,
          field2: &quot;Value2&quot;,
          field3: &quot;Value3&quot;,
         ...
         },
          ...
       ]
   }
          
  </code></pre>
  <p>I wanna count the number of elements of the array which have a certain condition (e.g. <code>field1: &quot;a&quot;</code>, and count all elements which have <code>field1 = a</code>).
  I'm trying with this code:</p>
  <pre><code>db.collection.aggregate([
  { $unwind : {path: &quot;$Array&quot;, 
               includeArrayIndex: &quot;arrayIndex&quot;}},
  { $match : { &quot;Array.field1&quot; : &quot;a&quot;}},
  { $project : { _id : 0, 
                 Array : 1, 
                 arrayIndex: 1, 
                 total: {$size: &quot;$Array&quot;}}}
  ])
  </code></pre>
  <p>but I receive this error:</p>
  <blockquote>
  <p>Command failed with error 17124: 'The argument to $size must be an
  array, but was of type: object' on server</p>
  </blockquote>
  <p>I looked for several answer to this problem, but I didn't find anything resolutive for my problem. I mean, 'Array' IS an array!</p>