Count(field) on Mongo

I have a collection of songs and its metadata with the following structure:

[{
    title:"title",
    artist:"artist",
    album:"album,
    ...
},...

Now I want to get a list of every artist with the number of songs and the number of albums it has using Node.js. So far, using the aggregation framework, I've been able to get an array of objects with each artist, its number of songs and an array with the album titles (instead of just the count), using the following pipeline:

collection.aggregate([
            { $project:{
                artist:1,
                album:1
            }},
            { $group: {
                _id: "$artist",
                songs:{$sum: 1},
                albums:{$addToSet:"$album"}
            }},
            { $sort: { artist: 1 } }
        ]

If I replace $addToSet with $sum, I get albums:0 in every artist, because it expects numbers and not strings to sum.

I just can't get around it!

You need to add a couple of steps to your pipeline - the array of albums needs to be unwound and then counted. Here is what it would look like:

collection.aggregate([
            { $project:{
                artist:1,
                album:1
            }},
            { $group: {
                _id: "$artist",
                songs:{$sum: 1},
                albums:{$addToSet:"$album"}
            }},
            { $unwind: "$albums"},
            { $group: {
                _id: "$_id",
                songs:{$first: 1},
                albums:{$sum: 1}
            }},
            { $sort: { artist: 1 } }
        ]
)