How to group by the first element of an array?

Unfortunately right now the only way to do this is to extract the $first element from the array after processing $unwind. Then of course you would have to $group again:

db.foobar.aggregate([
    { "$unwind": "$yearpublished" },
    { "$group": {
        "_id": "$_id",
        "yearpublished": { "$first": "$yearpublished" }
    }},
    { "$group": {
        "_id": "$yearpublished",
        "count": { "$sum": 1 }
    }}
])

Thats the only current way to get the "first" element from an array, by deconstructing it and using the operator to get the entry.

Future releases will have $arrayElemAt which can do this by index within a single stage:

db.foobar.aggregate([
    { "$group": {
        "_id": { "$arrayElemAt": [ "$yearpublished", 0 ] },
        "count": { "$sum": 1 }
    }}
])

But presently the aggregation framework does not deal with "dot notation" index usage such as standard "projection" with .find() does, and will not, hence the new operations.