I'm trying to count the number of occurrences of a string in an array in my collection using Mongoose. My "schema" looks like this:
var ThingSchema = new Schema({
tokens: [ String ]
});
My objective is to get the top 10 "tokens" in the "Thing" collection, which can contain multiple values per document. For example:
var documentOne = {
_id: ObjectId('50ff1299a6177ef9160007fa')
, tokens: [ 'foo' ]
}
var documentTwo = {
_id: ObjectId('50ff1299a6177ef9160007fb')
, tokens: [ 'foo', 'bar' ]
}
var documentThree = {
_id: ObjectId('50ff1299a6177ef9160007fc')
, tokens: [ 'foo', 'bar', 'baz' ]
}
var documentFour = {
_id: ObjectId('50ff1299a6177ef9160007fd')
, tokens: [ 'foo', 'baz' ]
}
...would give me data result:
[ foo: 4, bar: 2 baz: 2 ]
I'm considering using MapReduce and Aggregate for this tool, but I'm not certain what is the best option.
aggregate
unless you want the results persisted in their own collection. You'll want to look at the$unwind
operator for this.mapReduce
class has added the temporary operator to the query, allowing the resultset to be returned rather than persisted. Is there a reason beyond that that I'd want to useaggregate
instead?aggregate
is often dramatically faster.