Map/reduce query

I have a 3 Json Documents

Document 1

"No" : 1
"City" : "Patiala"
"Value" : 10

Document 2

"No" : 1
"City" : "Delhi"
"Value" : 11

Document 3

"No" : 1 
"City" : "Patiala"
"Value" : 11

I want output like

1    <Delhi or Patiala any one city>    32

I tried query with group level 2

map

function(doc, meta)
{
    emit([doc.No,doc.City],doc.Value);
}

reduce

_sum

and got output as

[1,Patiala]  21
[1,Delhi]    11

I only want to do group by on ‘No’ field but display any city.

Not sure I understand your question correctly but I think you could emit value as an array of doc.City and doc.Value. In the reduce, you will return an array of combined doc.City and doc.Value. The group level will be one.

If you don’t plan to sort by doc.City, you could drop it from the map function key as well.

Is this what you mean?
map

  function(doc, meta) 
{
           if(doc.No == 1)
           {
                        emit(doc.No,[doc.Value,doc.City]);
           }

}

reduce

_sum

I am getting the following error

Error building index for view my_first_view, reason: Value is not a number (key 1))

How do I write a query so that sum function works on only first value (ie value) and not on city?

You cannot use _sum function to combine the array. You need to write a reduce function. In the reduce function, you could loop over the values which is an array of [city,value] to combine city (in the format that you want) and sum the value. The return value will be [combined cities, total value]

Hi,

map function

function(doc, meta)
{
    emit(doc.No,[doc.Value,doc.City]);
}

Below is the reduce function I wrote

function(key,values,rereduce){
   if(!rereduce){
   var sum=0;
   var s=[];
   var v=[];
   v=values[1];
   s=values[0];
   for(i=0;i<s.length;++i)
  {
         sum+= s[i];
   }
  return (sum,v[0]);
}
else{
   var sum=0;
   var s=[];
   var v;
   v=values[1];
   s=values[0];
   for(i=0;i<s.length;++i)
   {
   
       sum+= s[i];
    }
   return (sum,v);
   }  
}

and I am getting the following error

(Reducer: Error building index for view my_first_view, reason: TypeError: Cannot read property ‘length’ of null)