0

I have view map and reduce like this: Map:

   function(doc) {
           if(doc.type){
            var usersLength = doc.users.length;
            for (var i = 0; i < usersLength ; i++) {
                    emit([doc.users[i].userid,doc.Service.ownId], 1);
                }
            }
        }

Reduce:

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

Then invoke the view like this: _design/aaa/_view/getUserId?group=true&group_level=2&startkey=["111111"]&endkey=["111111",{}]

I can get the result set below:

{"rows":[
{"key":["111111",""],"value":7},
{"key":["111111","FFFF26"],"value":1},
{"key":["111111","FFFF44"],"value":7},
{"key":["111111","FFFF34"],"value":2}
]}

However, I want to get the result set above sorted within descending order of the "value" value. if also using list function can achieve that? the following would be expected results:

{"rows":[
{"key":["111111",""],"value":7},
{"key":["111111","FFFF44"],"value":7},
{"key":["111111","FFFF34"],"value":2},
{"key":["111111","FFFF26"],"value":1}
]}
Jamesjin
  • 371
  • 2
  • 6
  • 15
  • CouchDB will only sort your view based on the key, which is what it's designed to do. If you want to sort by the value as well, you can use a list function as you mentioned already. – Dominic Barnes Aug 08 '16 at 07:21

1 Answers1

2

If you want to sort the result set you have to one that is sorted by value descending you can sort with a comparator callback:

// ES6 Syntax
let originalResult = {
"rows":[
  {"key":["111111",""],"value":7},
  {"key":["111111","FFFF26"],"value":1},
  {"key":["111111","FFFF44"],"value":7},
  {"key":["111111","FFFF34"],"value":2}
]}

let newResult = {
  rows: originalResult.rows.sort((a, b) => b.value - a.value)
} 
Damon
  • 4,216
  • 2
  • 17
  • 27
  • 1
    thanks you for your good suggestion, how can do this new results set within a map/reduce view? – Jamesjin Aug 06 '16 at 03:55
  • Thanks, I think I will use list function achieve on this – Jamesjin Aug 08 '16 at 07:26
  • Hey Jamesjin, sorry nobody has answered your question based on what you are looking for. Unfortunately I do not know couchdb so I can't help you there, but I would say this sounds like something you an do with a query. – Damon Aug 08 '16 at 12:34