I have a collection that looks something like this:
{ "_id": "id0", "name": "...", "saved_things": [ { ... }, { ... }, { ... }, ] } { "_id": "id1", "name": "...", "saved_things": [ { ... }, ] } { "_id": "id2", "name": "...", "saved_things": [ { ... }, ] }
etc...
I want to use the mongodb aggregation structure to get a histogram result that tells how many users have a certain number of saved_things . For example, for the dataset above, it might return something like:
{ "_id": 1, "count": 2 }, { "_id": 3, "count": 1 }
I tried various combinations of aggregate functions like the ones below, but none of them worked out correctly. (I have the feeling that I'm terribly wrong about that.)
collection.aggregate([ { $unwind: "$saved_things" }, { $group: "$_id", count: { $sum: 1 } } }, { $group: "$count", number: { $sum: 1 } } }, { $sort: { number: -1 } } ], function(err, result) { console.log(result); });
Is this possible with the Mongo aggregate structure, or will I be better off with the map reduction feature?