Suppose I have this structure:

{name : 'John', group : [one, two]} {name : 'Dony', group : [one, three]} 

And I need to output: one - 2, two - 1, three - 1

How to implement it in MongoDB?



    2 answers 2

    This is done using MapReduce , see the second example.

    For your collection it will look

    map function

     > m = function() { ... this.group.forEach( ... function(name){ ... emit( name , { count : 1 } ); ... } ... ); ... }; 

    reduce function

     > r = function( key , values ){ ... var total = 0; ... for ( var i=0; i<values.length; i++ ) ... total += values[i].count; ... return { count : total }; ... }; 

    Launch MapReduce

     db.test.mapReduce(m, r, { out : "myoutput" } ); 

    and the result is stored in the "myoutput" collection

     > db.myoutput.find() { "_id" : "one", "value" : { "count" : 2 } } { "_id" : "three", "value" : { "count" : 1 } } { "_id" : "two", "value" : { "count" : 1 } } 
    • one
      Infa for beginners - try to avoid active use of MapReduce, if such a format is so important and 100% accuracy of the data is not important - it is better to do aggregation somewhere on the slave over a certain interval. - Zowie

    Not strong in MongoDB, but for example in ElasticSearch for this there is a facet data request (Facets). Quite simply and conveniently gives just such statistical information. Google for "Facets MongoDB" also gives out something