edoceo

CouchDB Views

CouchDB views are very powerful as they are based on a map/reduce operation. However, these "views" are not like those in traditional relational database systems.

One common scenario is to list all items in a database of a specific type, by name. So, lets say we have set of objects in couchdb; some that have a "city" property to show what city that object is in; and others that have a "kind" property that is city. By examinging all documents with a city, or all the city objects we can get the list of cities. This will require mapping first, to output city names (the key) and the reducing = so that the items are only shown with one record

Map those to fields to the key as follows.

function(d) {
    if (d.city) emit(d.city, { _id:null });
    if (d.kind=="city") emit(d.name, { _id:d._id });
}

And reduce them, to only show the _id field like this

function (k,v,r) {
    for (var x in v) {
        ret = (v ? v : 'Beer' );
    }
    return (ret);
}








Loading Comments from Disqus...