3

I am wondering how to use CouchDB's map/reduce with multiple parameters. For example, if I have teams that have players with ages and genders, I assume I would do this for my map function:

"function(doc){
  if(doc.team_name) {
    emit(doc.team_name, doc);
  }
}"

However, I am unsure how to write a reduce function to get the oldest male player on the team or the youngest female or whatever arbitrary query. Can I pass in parameters in the URL or do I have to write multiple views?

Thanks in advance,
Ben

user21293
  • 6,439
  • 11
  • 44
  • 57

1 Answers1

5

Reduce function has a bit different purpose. Reduce function is grouping some value for all the documents it processes. So you can e.g. sum players salaries, or age, or count them.

If you want to get the oldest player in the team, just set your key in emit function to [team, age]. View is always sorted by key.

function(doc) {
  if (doc.team_name) {
    emit([doc.team_name, doc.age], doc);
  }
}

now just query your view. Add parameter descending=true, so the oldest player is the first. By default view order is ascending. If you want to get players in specific team (still sorted by age) add parameters: startkey=[<team>, 999]&endkey=[<team>,0]&descending=true

amorfis
  • 15,390
  • 15
  • 77
  • 125
  • 1
    Wouldn't the result of this be a list sorted after the team name rather than the age of the team? My suggestion is: emit([doc.age, doc.team_name], doc); – javabeangrinder Jan 03 '13 at 14:00