$unwind: One Document per Array Value
How many movies are there in each genre? $group cannot answer this directly, because genres is an array. $unwind helps. It turns one document with an array of N values into N documents, each with one value:
db.movies.aggregate([
{ $match: { _id: 1 } },
{ $unwind: "$genres" },
{ $project: { _id: 0, title: 1, genres: 1 } }
])
Output:
[
{ title: 'Inception', genres: 'sci-fi' },
{ title: 'Inception', genres: 'thriller' }
]
Inception went in once, with two genres. It came out twice, with one genre in each copy. Now each genre is a plain value, and $group can group by it:
db.movies.aggregate([
{ $unwind: "$genres" },
{ $group: {
_id: "$genres",
titles: { $push: "$title" }
} },
{ $sort: { _id: 1 } }
])
Output:
[
{
_id: 'drama',
titles: [ 'Interstellar', 'Parasite', 'Whiplash', 'Okja', 'First Man' ]
},
{ _id: 'history', titles: [ 'First Man' ] },
{ _id: 'music', titles: [ 'Whiplash', 'La La Land' ] },
{ _id: 'romance', titles: [ 'La La Land' ] },
{ _id: 'sci-fi', titles: [ 'Inception', 'Interstellar' ] },
{ _id: 'thriller', titles: [ 'Inception', 'Parasite', 'Dunkirk' ] },
{ _id: 'war', titles: [ 'Dunkirk' ] }
]
Each genre now has the list of movies in it. $push collected the titles into an array. To count instead of listing, use $sum: 1 like in the group lesson.
Two things to know. A document whose array is empty, or that has no such field, disappears at $unwind. Also, unwinding makes more documents, so put $match before $unwind when you can.
In the exercise, count the movies in each genre.