I am starting to learn MongoDB and I am working with such documents:
{ "_id" : ObjectId("562fac8a4f9ecec40f5b8ff9"), "foo" : { "objectid" : "39", "stuff" : "65" }, "yearpublished" : [ "1979" ], "bar": "1263" }
yearpublished is an array, and I would like to group my collection by the first value in this array, and then count the number of related documents.
I already made this request:
db.foobar.aggregate( [ { $group : { _id : '$yearpublished', count: { $sum: 1 } } } ] )
and get:
{ "result" : [ { "_id" : [ "1923" ], "count" : 1.0000000000000000 }, { "_id" : [ "1864" ], "count" : 1.0000000000000000 } }
But I am looking for such a result (for example, only the first element):
{ "result" : [ { "_id" : "1923, "count" : 1.0000000000000000 }, { "_id" : "1864", "count" : 1.0000000000000000 } }
I tried _id : { $first: '$yearpublished.0' }, or _id : { $first: '$yearpublished[0]' }, without success.
Do you know if I can group the first element of a yearpublished array?