How to group by the first element of an array with MongoDB?

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?

+5
source share
1 answer

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

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

This is the only way to get the "first" element from an array by deconstructing it and using the operator to get the record.

Future releases will have $arrayElemAt , which can do this by index in one step:

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

But at present, the aggregation structure does not apply to the use of the “point of note” index, for example, to the standard “projection” using .find() , and therefore there will be no new operations.

+7
source

Source: https://habr.com/ru/post/1234685/


All Articles