Search code examples
couchdbcloudantcouchdb-futoncouchdb-2.0couchdb-mango

couchdb : implement joins and views


I need to get below Result by joining Person and Department using CouchDB views and joins. How can this be achieved?

Person: {
    name: 'Parnika',
    city: 'Delhi',
    dept: 'DevOps'
}

Department: {
    name: 'DevOps',
    city: 'Delhi'
}

Result: {
    Person: {
        name: 'Parnika'
        city: 'Delhi',
        Department: {
            name: 'DevOps',
            city: 'Delhi'
        }
    }
}

Solution

  • Instead of starting with "how do I do a join" (no relational joins as such in couchdb), start with what you want to achieve. For example, perhaps what you are trying to do is to map people to departments.

    Look to denormalise your data so that each document contains all the data you expect from a row in a relational join:

    Person: {
        name: 'Parnika'
        city: 'Delhi',
        Department: {
            name: 'DevOps',
            city: 'Delhi'
        }
    }
    

    Now you can create a view that maps Department.name to Person.name, something like

    function(doc) {
        if (doc && doc.name && doc.Department && doc.Department.name) {
            emit(doc.Department.name, doc.name);
        }
    }
    

    This view will let you find people grouped by department.