MongoDB group by array inner-elements
Solution 1:
What framework are you using? This is not MongoDB shell and looks like some weird wrapper around MapReduce. In that case $unwind would not be available, and you need it for user in the aggregation framework. Here's what you want in the mongo shell:
db.articles.aggregate([
{$match: { class_date: { $gte: date } } },
{$project: { _id: 0, class_artist: 1 } },
{$unwind: "$class_artist" },
{$group: { _id: "$class_artist", tags: { $sum: 1 } }},
{$project: { _id: 0,class_artist: "$_id", tags: 1 } },
{$sort: { tags: -1 } }
])
So efficiently:
- Filter by date because you already set a var for the last 7 days
- Project only the field(s) we need { We need only one! }
- Unwind the array so we now have a record for every array element in every document
- Group on the Artist from the expanded documents
- Project into a document format you can use as group messed around with _id
- Sort the results in reverse order to see the top tagged first
And the great thing about aggregation is you can gradually build up those stages to see what is going on.
Shake and bake into your own driver implmentation or ODM framework as required.