couchdb-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Paweł Stawicki <pawelstawi...@gmail.com>
Subject Re: returning document list and a count of related documents
Date Tue, 15 Dec 2009 23:36:39 GMT
Hmm... Maybe try to have document as a key?

// map.js
function(doc) {
 if (doc.type == "post") {
   map(doc, 0);
 } else if (doc.type == "comment") {
   map({'_id':doc.post}, 1);
 }
}

// reduce.js
function(keys, values, rereduce) {
       return sum(values);
}


Then call view with "group=true" parameter. You should get document as
key, and number of comments as value.

Another solution, if you need post id as a key and post document as value:
// map.js
function(doc) {
 if (doc.type == "post") {
   map(doc._id, [doc, 0]);
 } else if (doc.type == "comment") {
   map(doc.post, [{'_id':doc.post}, 1]);
 }
}

// reduce.js
function(keys, values, rereduce) {
  if (!rereduce) {
    var commentsCount = 0;
    values.forEach(function(array) {
      commentsCount += array[1];
    }
    return [values[0][0], commentsCount;
  } else {
    var commentsCount = 0;
    values.forEach(function(array) {
      commentsCount += array[1];
    }
    return [values[0], commentsCount;
  }
}

WARNING: will work only with "group=true" parameter.

I am not sure it will work, but it definitely won't work with
group_level = 0 (which is default), so use group=true. It should give
you post id as a key, and post document and comments count as value.


Regards
-- 
Paweł Stawicki
http://pawelstawicki.blogspot.com
http://szczecin.jug.pl
http://www.java4people.com

Mime
View raw message