1

I need to create a view that lists the values for an attribute of a doc field.

Sample Doc:

{
   "_id": "003e5a9742e04ce7a6791aa845405c17",
   "title", "testdoc",
   "samples": [
       {
           "confidence": "high",
           "handle": "joetest"
       }
   ]
}

Example using that doc, I want a view that will return the values for "handle"

I found this example with the heading - Get contents of an object with specific attributes e.g. doc.objects.[0].attribute. But when I fill in the attribute name, e.g. "handle" and replace doc.objects with doc.samples, I get no results:

Toggle line numbers
// map
function(doc) {
  for (var idx in doc.objects) {
    emit(doc.objects[idx], attribute)
  }
}

2 Answers 2

2

That will create an array of key-value-pairs where the key is alway the value of handle. Replace null with a value you want e.g. doc.title. If you want to get the doc attached to every row use the query parameter ?include_docs=true while requesting the view.

// map
function (doc) {
  var samples = doc.samples
  for(var i = 0, sample; sample = samples[i++];) {
    emit(sample.handle, null)
  }
}
Sign up to request clarification or add additional context in comments.

6 Comments

Oh. I have misread your example doc. Samples is an array. I will update my answer.
That's excellent, thank you llabball. Can I use a startkey with this setup or will I need to filter in my python app?
The list is sorted be the keys. You can request a range with the query params ?startkey="..."&endkey="..."
Awesome, thanks again llabball. In truth I'm using the results of this view as a base to find matches across records that have the same handle value in their sample lists. If there's a possibility of doing that in a view rather than in code, I can create another question and post the link.
Yes, its possible to use a reduce step. Create a new question.
|
2

Like this ->

function(doc) { 
    for (var i in doc.samples) {
      emit(doc._id, doc.samples[i].handle)
    }   
}

It will produce a result based on the doc._id field as the key. Or, if you want your key to be based on the .handle field you reverse the parameters in emit so you can search by startKey=, endKey=.

5 Comments

^5 We ended with almost the same answer :-)
Thanks sebster. I would accept both but I can't. I upvoted both instead.
Heh, yeah... well, it's not like we had to many ways to go about this. Actually wait, we had... with all the for types in javascript
@Jon Reid Thanks, but he was faster so his answer should be accepted anyway. Upvoting his answer as well.
This is how SO should be, mate :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.