开发者

How order a view result by reduced value? CouchDB

开发者 https://www.devze.com 2022-12-23 05:49 出处:网络
Can I order the result of a view by the value, returned by reduced? { \"rows\": [ {\"key\":\"bob\",\"value\":2},

Can I order the result of a view by the value, returned by reduced?

{
    "rows": [
        {"key":"bob","value":2},
        {"key":"john","value":3},
        {"key":"zztop","value":1}
     ]
}

I wanna a result like this:

{
    "rows": [
        {"key":"zztop","value":1},
        {"key":"bob","value":2},
        {"key":"john","value":3}

     ]
}
开发者_开发技巧


you just want to sort the rows array by the value property of each object? you can specify a custom comparison method for the js sort method.

myResult.rows.sort(function (a, b) {
    return parseInt(a.value,10) - parseInt(b.value,10);
});

parameters a and b will each be an entry from the rows array. the method returns an int value of greather than 0, 0, or less than zero. greater than 0 means a should be ordered before b, the opposite for less than 0, and 0 means they are equal.


I would just build it into the key...

{"key": [1, "zztop"], "value": "whateverYouWant"},
{"key": [2, "bob"], "value": "whateverYouWant"},
{"key": [3, "john"], "value": "whateverYouWant"}

In order to search for a specific key, use a startkey/endkey query like this:

http://XXXXXX/database/_design/name/_view/name?startkey=[[0,"zztop"]]&endkey=[[999,"zztop"]]

As long as your value is numerical, just make the endkey larger than the largest possible value and this query should return the results for "zztop."

It's sloppy, but I have yet to find a better CouchDB sorting method. All-in-all, you might be better sorting in your application.

0

精彩评论

暂无评论...
验证码 换一张
取 消