Mongoose / MongoDB: the number of elements in the array

I am 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 goal is to get the top 10 โ€œtokensโ€ in the โ€œThingโ€ collection, which can contain multiple values โ€‹โ€‹for each document. For instance:

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 the result of the data:

[ foo: 4, bar: 2 baz: 2 ]

I am considering using MapReduce and Aggregate for this tool, but I'm not sure if this is the best option.

+5
source share
1 answer

, . MongoDB aggregate . $unwind, , / .

MongooseJS . , :

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 ]
});

, MapReduce ~ 200 000 , , , , , . YMMV.

+19

All Articles