couchdb-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Tobi Schäfer <interf...@p3k.org>
Subject Newbie question: How to collate sum() with other properties
Date Fri, 06 Jan 2012 14:09:41 GMT
Hello

I am developing a little survey / poll tool as a first step in practicing CouchDB.

There are poll and vote documents stored in the database:

poll = {
   _id: 'd193f1137ddb65aa14100a51dc61b17e',
   type: 'poll',
   title: 'What is the question?',
   choices: ['Choice 1', 'Choice 2, 'Choice 3'],
   date: new Date
}

vote = {
   poll_id: 'd193f1137ddb65aa14100a51dc61b17e',
   type: 'vote',
   choice: 'Choice 1',
   date: new Date
}

Now I am trying to create a view of all polls together with their aggregated votes for each
choice as well as the total votes:

map: function(doc) {
   if (doc.type === 'poll') {
      emit([doc._id, doc.date], {title: doc.title});
   } else if (doc.type === 'vote' && doc.choice) {
      emit([doc.poll_id, doc.choice], {count: 1, title: doc.choice});
      emit([doc.poll_id, '_total'], {count: 1, title: doc.choice});
   }
},

reduce: function(key, values) {
   var i, value, result = {count: 0};
   for (i in values) {
      value = values[i];
      result.title = value.title;
      if (value.count) {
         result.count += 1;
      } else {
         delete result.count;
      }
   }
   return result;
}

This seems to work but I am not sure if I will run into “rereduce trouble”:

["d193f1137ddb65aa14100a51dc235509", "2012-01-05T15:36:40.632Z"]
{title: "What is the amazingly accurate answer to the ultimate question of life, the universe
and everything?"}
["d193f1137ddb65aa14100a51dc235509", "_total"]		{count: 7, title: "6 · 9"}
["d193f1137ddb65aa14100a51dc235509", "101010"]	{count: 2, title: "101010"}
["d193f1137ddb65aa14100a51dc235509", "42"]			{count: 3, title: "42"}
["d193f1137ddb65aa14100a51dc235509", "6 · 9"]		{count: 1, title: "6 · 9"}
["d193f1137ddb65aa14100a51dc235509", "XLII"]		{count: 1, title: "XLII"}

What do you think? Is there an easier or more convenient way to create such a view?

Best regards,
Tobi Schäfer


Mime
View raw message