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?
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?
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 } }
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
Source: https://ru.stackoverflow.com/questions/140557/