title: CouchDB view collation, join on one key, search on other values
body: <p>Looking at the example described in <a href="http://www.cmlenz.net/archives/2007/10/couchdb-joins" rel="nofollow">Couch DB Joins</a>.</p>
  
  <p>It discusses view collation and how you can have one document for your blog posts, and then each comment is a separate document in CouchDB. So for example, I could have <em>"My Post"</em> and 5 comments associated with <em>"My Post"</em> for a total of 6 documents. In their example, <em>"myslug"</em> is stored both in the post document, and each comment document, so that when I search CouchDB with the key <em>"myslug"</em> it returns all the documents.</p>
  
  <p>Here's the problem/question. Let's say I want to search on the author in the comments and a post that also has a category of <em>"news"</em>.  How would this work exactly?</p>
  
  <p>So for example:</p>
  
  <pre><code>function(doc) {
    if (doc.type == "post") {
      emit([doc._id, 0], doc);
    } else if (doc.type == "comment") {
      emit([doc.post, 1], doc);
    }
  }
  </code></pre>
  
  <p>That will load my blog post and comments based on this: <code>?startkey=["myslug"]</code></p>
  
  <p>However, I want to do this, grab the comments by author <em>bob</em>, and the post that has the category <em>news</em>. For this example, <em>bob</em> has written three comments to the blog post with the category <em>news</em>. It seems as if CouchDB only allows me search on keys that exist in both documents, and not search on a key in one document, and a key in another that are <em>"joined"</em> together with the map function.</p>
  
  <p>In other words, if post and comments are joined by a slug, how do I search on one field in one document and another field in another document that are joined by the id aka. slug?</p>
  
  <p>In SQL it would be something like this:</p>
  
  <pre class="lang-sql prettyprint-override"><code>SELECT * FROM comments JOIN doc.id ON doc.post WHERE author = bob AND category = news
  </code></pre>