简体   繁体   中英

Sum values in CouchDB documents

So assume I have the following two documents in CouchDB:

{
   "_id": "197000000002",
   "_rev": "1-fbe819b01108f30d2e9e96f3fb46eff8",
   "country": "130",
   "region": "1",
   "country_txt": "Mexico",
   "nkill": "1",
}

{
       "_id": "197000000003",
       "_rev": "1-fbe819b01108f30d2e9e96f3fb46eff8",
       "country": "130",
       "region": "2",
       "country_txt": "Mexico",
       "nkill": "3",
    }

And I want to create a view that returns me something like this:

Key: Mexico, Value: 4

And this has to happen for every other country, so all of the values in nkill need to be summed together based on the country.

I tried the following Map Function:

function(doc) {
 if(doc.nkill >= 1){
  emit(doc.country_txt,doc.nkill);
}
}

And the following Reduce Function:

function(keys,values,rereduce) {
  return sum(values);
}

But so far I can't get the desired result that I am looking for, what am I doing wrong and how can I get the result that I am looking for?

Your property nkill is stored a string.

I assume the sum() function is either concatening the string or doing something else that summing numbers.

You can try to concert your values to numbers in your map function and it should work.

Also, you should use the _sum internal reduce function if you want to sum something. It's way faster as it runs internally with Erlang.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM