couchdbcouchdb-mango

Map/reduce in CouchDB take a field if id contains a subString


I'll explain: I have this function

function (doc) {
  if(doc.MovieId == "1721")
  emit(doc.Rating, 1);
}

but it return me some document that are not relevant (for example they haven't the Rating field). My document _id is composed of partitionName:id, so I thought to do if(doc.MovieId == "1721" && doc._id.contains("ratings"){...} but it doesn't work. Is there a way to do this?

-----EDIT 1----- documents without a field named "Rating" The docs in the circle are not relevant. Do you need the schema of the JSON document?

-----EDIT 2----- the following documents are NOT RELEVANT 1.

{
  "_id": "movies : 1721",
  "_rev": "1-d7e0e3c8152d6978073d280e0aef7457",
  "MovieId": "1721",
  "Title": "Titanic (1997)",
  "Genres": [
    "Drama",
    "Romance"
  ]
}

2.

{
  "_id": "tags : 1490",
  "_rev": "1-14c20c9cfb3ee1964a298777f80333d5",
  "MovieId": "1721",
  "UserId": "474",
  "Tag": "shipwreck",
  "Timestamp": "1138031879"
}

3.

{
  "_id": "tags : 2791",
  "_rev": "1-e4d6c9573fcdae726a69d5fc6255de27",
  "MovieId": "1721",
  "UserId": "537",
  "Tag": "romance",
  "Timestamp": "1424141922"
}

documets like this are RELEVANT:

{
  "_id": "ratings : 31662",
  "_rev": "1-446665286337faaf51e23e40b527ec2d",
  "MovieId": "1721",
  "UserId": "219",
  "Rating": "0.5",
  "Timestamp": "1214043346"
}

Solution

  • Following view should just emit documents whose _id starts with "ratings :":

    function (doc) {
      var id_prefix = "ratings :";
    
      if(doc._id.substr(0, id_prefix.length) === id_prefix && doc.MovieId == "1721")
      emit(doc.Rating, 1);
    }