title: $group inner array values without $unwind
body: <p>I want to group objects in the array by same value for specified field and produce a count.</p>
  
  <p>I have the following mongodb document (non-relevant fields are not present).</p>
  
  <pre><code>{
    arrayField: [ 
      { fieldA: value1, ...otherFields }, 
      { fieldA: value2, ...otherFields },
      { fieldA: value2, ...otherFields } 
    ],
    ...otherFields
  }
  </code></pre>
  
  <p>The following is what I want.</p>
  
  <pre><code>{
    arrayField: [ 
      { fieldA: value1, ...otherFields }, 
      { fieldA: value2, ...otherFields },
      { fieldA: value2, ...otherFields } 
    ],
    newArrayField: [ 
      { fieldA: value1, count: 1 }, 
      { fieldA: value2, count: 2 },
    ],
    ...otherFields
  }
  </code></pre>
  
  <p>Here I grouped embedded documents by fieldA.</p>
  
  <p>I know how to do it with unwind and 2 group stages the following way. (irrelevant stages are ommited)</p>
  
  <p>Concrete example</p>
  
  <pre><code>// document structure
  {
    _id: ObjectId(...),
    type: "test",
    results: [ 
      { choice: "a" }, 
      { choice: "b" },
      { choice: "a" } 
    ]
  }
  </code></pre>
  
  <pre><code>db.test.aggregate([
  { $match: {} },
  {
    $unwind: {
      path: "$results",
      preserveNullAndEmptyArrays: true
    }
  },
  {
    $group: {
      _id: {
        _id: "$_id",
        type: "$type",
        choice: "$results.choice",
      },
      count: { $sum: 1 }
    }
  },
  {
    $group: {
      _id: {
        _id: "$_id._id",
        type: "$_id.type",
        result: "$results.choice",
      },
      groupedResults: { $push: { count: "$count", choice: "$_id.choice" } }
    }
  }
  ])
  </code></pre>