Jitender Pal Singh
Jitender Pal Singh

Reputation: 48

couchdb joins for 2 documents

I am new to couchdb and I need to make a join and get results from 2 documents type.

I have type="registeredEvent" in one document and type="user" in another. The schema of both the type are as follows:

registeredEvent

{
   "_id": "316ff4844ce56...",
   "_rev": "2-5dcfb85eaea3f....",
   "eventid": "0620F01F-3B6B-DE07-860A-SF453FF5AELP11",
   "email": "[email protected]",
   "type": "registeredEvent"
}

Users

{
   "_id": "[email protected]",
   "_rev": "1-89768208cfb5650ee....",
   "name": "amaya",
   "email": "[email protected]",
   "dob": "91-07-14",
   "gender": "Female",
   "location": "canada",
   "facebook": "dghdfj",
   "twitter": "fgfghh",
   "type": "user"
}

I want to get data for populating a graph.

  1. I have a list of eventid's and I want to get count of females in those events.
  2. I also want to have the no of users in each of these events but are in the age group 17-28

I am using the following to fetch data

db.query('event/getGraphdata1...',{keys: [<array of eventid's>], include_docs: true })

Can anybody help me out. I have tried a number of things but of no success. I could not check if I am on the right track as all the things provided me with wrong data.

Upvotes: 2

Views: 120

Answers (2)

Wiz
Wiz

Reputation: 44

You can get data of gender, age using list like:

function(head, req) { 
       var row; var counts = {}; var male = female = age18 = 0;
       while(row = getRow()) {
         if(row.doc != null) { 
            if(row.doc.gender != null && row.doc.gender.toLowerCase() === 'male') 
                male++; 
            else 
                female++;
            if(row.doc.dob != null && Array.isArray(row.doc.dob)) { 
                var age = 0;
                var date1 = new Date(row.doc.dob[0], row.doc.dob[1], row.doc.dob[2]);
                var date2 = new Date();  var m = date1.getMonth(); 
                var years = date2.getFullYear() - date1.getFullYear(); 
                date1.setFullYear(date1.getFullYear() + years); 
                if (date1.getMonth() != m) date1.setDate(0); 
                age = date1 > date2 ? --years : years; 

                if(age < 29) 
                    age18++;
            }
         }
     }
     counts['male'] = male;counts['female'] = female; counts['age18'] = age18; send(JSON.stringify({'counts' : counts}))
 }

You can extend this to support more age groups if needed...

Upvotes: 1

Wiz
Wiz

Reputation: 44

You can get one result set from these 2 document using following view:

function(doc) {
  if (doc.type === 'registeredEvent') {
     emit(doc.eventid, {_id:"Profile_" + doc.email}, doc.user);
   }
}

When requesting using HTTP API add include_docs=true

Upvotes: 1

Related Questions