0

This has kept me awake until these wee hours. I want a db to keep track of a soccer tournament. Each match has two teams, home and away. Each team can be the home or the away of many matches.

I've got one db, and two document types, "match" (contains: home: teamId and away: teamId) and team (contains: teamId, teamName, etc).

I've managed to write a working view but it would imply adding to each team the id of every match it is involved in, which doesn't make much logical sense - it's such an hack.

Any idea on how this view should be written? I am nearly tempted to just throw the sponge in and use postgres instead.

EDIT: what I want is to have the team info for both the home and away teams, given the id of a match. Pretty easy to do with two calls, but I don't want to make two calls.

Barbara Jacob
  • 286
  • 4
  • 11

2 Answers2

1

Just emit two values in map for each match like this:

function (doc) {
  if (!doc.home || !doc.away) return;
  emit([doc._id, "home"], { _id: doc.home });
  emit([doc._id, "away"], { _id: doc.away });
}

After querying the view for the match id MATCHID with:

curl 'http://localhost:5984/yourdb/_design/yourpp/_view/yourview?startkey=\["MATCHID"\]&endkey=\["MATCHID",\{\}\]&include_docs=true'

you should be able to get both teams' documents in doc fields in list of results (row), possibly like below:

{"total_rows":2,"offset":0,"rows":[
{"id":"MATCHID","key":["MATCHID","home"],"value":{"_id":"first_team_id"},"doc":{...full doc of the first team...}},
{"id":"MATCHID","key":["MATCHID","away"],"value":{"_id":"second_team_id"},"doc":{...full doc of the second team...}}
]}
Marcin Skórzewski
  • 2,854
  • 1
  • 17
  • 27
  • Thank you Marcin - I haven't tried it yet but it looks like your solution is viable. – Barbara Jacob Aug 24 '12 at 21:23
  • Indeed - your solution was right. I didn't manage to make the startkey/endkey part work, but I am such a noob in couchdb that probably I was doing something trivially wrong. My view looks like this: function(doc){ if(doc.recordType == 'match'){ emit(doc._id, {'_id':doc.home}); emit(doc._id, {'_id':doc.away}); emit(doc._id, {'_id':doc._id}); } } and can be interrogated through `key="matchIdHere"` Wow, thank you a lot, it's a big relief to have managed :) – Barbara Jacob Aug 27 '12 at 01:36
0

Check the CouchDB Book: http://guide.couchdb.org/editions/1/en/why.html

It's free and includes answers to a beginner :)

If you like it, consider buying it. Even thought Chris and Jan are so awesome they just put their book out there for free you should still support the great work they did with their book.

dscape
  • 2,506
  • 1
  • 22
  • 20