In couchdb I need to filter by key and which is done like this.
{
"_id": "_design/test",
"_rev": "6-cef7048c4fadf0daa67005fefe",
"language": "javascript",
"views": {
"all": {
"map": "function(doc) { if (doc.blogId) {emit(doc.key, doc);} }"
}
}
}
However the results should be ordered by another key (doc.anotherkey). So using the same function how do I achieve both filtering and ordering by another key.
Thank you
If you only need to query by single
key, you can use the following map:and query for
"KEY"with?startkey=["KEY"]&endkey=["KEY",{}]&include_docs=true.Here, according to the collation specification of CouchDB:
["KEY"]is a value lesser than any["KEY","OTHER"]value (because longer arrays sort after their prefixes), but greater than any["KEY2","OTHER"]with"KEY2" < "KEY";["KEY",{}]is a value greater than any["KEY","OTHER"]value, ifdoc.otherkeyis never a JSON object (because JSON objects comes after any other JSON value), but lesser than any["KEY2","OTHER"]with"KEY2" > "KEY".Of course this is not limited to strings. Any type of value will work, as long as the collation is right.
Remember to URL encode the values in
startkeyandendkey. For example, usingcurland assuming your database is “DB”:Note that I’ve used the
include_docsquery parameter, instead of emitting the entire document withemit(..., doc), to save disk space. Query parameters are documented on CouchDB documentation.To sort results in descending order, use the
descending=truequery parameter and swap the values ofstartkeyandendkeyas documented in the definitive guide book.