Note that there are some explanatory texts on larger screens.

plurals
  1. POMap/Reduce to get group() Result
    primarykey
    data
    text
    <p>I'm trying to aggregate a bunch of user profile data in our app. Each user has an embedded profile document with a gender, and ethnicity attribute.</p> <pre><code>{ 'email': 'foo@email.com', 'profile': { 'gender': 'male', 'ethnicity': 'Hispanic' } } </code></pre> <p>If I use a group function like so:</p> <pre><code>db.respondents.group({ key: {}, initial: {'gender': {'male':0,'female':0}, 'ethnicity': {}, 'count': 0}, reduce: function (user, totals) { var profile = user.profile; totals.gender[profile.gender]++; totals.ethnicity[profile.ethnicity] = (totals.ethnicity[profile.ethnicity] || 0); totals.ethnicity[profile.ethnicity]++ totals.count++; } }); </code></pre> <p>I get the result in the form I want:</p> <pre><code>{ "gender" : { "male" : ###, "female" : ### }, "ethnicity" : { "Caucasian/White" : ###, "Hispanic" : ###, ... }, "count" : ### } </code></pre> <p>I'm having trouble getting this to work as a map/reduce command, using a different reduce function of course. I'm not sure how to get the totals to add up. They are always incorrect. I'm aware that my output from reduce has to be in the same format as the input from map, but I feel like I'm missing something in the way that reduce works...</p> <p>In response to @Jenna, the input looks like:</p> <pre><code>{ 'email': 'foo@email.com', 'profile': { 'gender': 'male', 'ethnicity': 'Hispanic' } } </code></pre> <p>and the functions are:</p> <pre><code>function map(){ emit('demographics', this.profile) } function reduce (key, values) { var reduced = {'gender': {'male':0,'female':0}, 'ethnicity': {}, 'count': 0}; values.forEach(function(value) { reduced.gender[value.gender]++; reduced['ethnicity'][value.ethnicity] = (reduced['ethnicity'][value.ethnicity] || 0); reduced['ethnicity'][value.ethnicity]++; reduced.count++; }); return reduced; } </code></pre> <p>and the output is: </p> <pre><code>{ "_id": "demographics", "value": { "gender": { "male": 76.0, "female": 64.0 }, "ethnicity": { "Caucasian/White": 109.0, "Other": 5.0, "Asian": 10.0, "African-American": 8.0, "Hispanic": 7.0, "Native American": 1.0 }, "count": 141.0 } } </code></pre> <p>The output is way incorrect since there are over 100k records in the database.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload