Mongoose / MongoDB: count elements in array
Aha, I've found the solution. MongoDB's aggregate
framework allows us to execute a series of tasks on a collection. Of particular note is $unwind
, which breaks an array in a document into unique documents, so they can be groups / counted en masse.
MongooseJS exposes this very accessibly on a model. Using the example above, this looks as follows:
Thing.aggregate([ { $match: { /* Query can go here, if you want to filter results. */ } } , { $project: { tokens: 1 } } /* select the tokens field as something we want to "send" to the next command in the chain */ , { $unwind: '$tokens' } /* this converts arrays into unique documents for counting */ , { $group: { /* execute 'grouping' */ _id: { token: '$tokens' } /* using the 'token' value as the _id */ , count: { $sum: 1 } /* create a sum value */ } }], function(err, topTopics) { console.log(topTopics); // [ foo: 4, bar: 2 baz: 2 ]});
It is noticeably faster than MapReduce in preliminary tests across ~200,000 records, and thus likely scales better, but this is only after a cursory glance. YMMV.