Using mysql this would be:
SELECT * FROM thetable ORDER BY id DESC LIMIT 10
How can I do this in couchdb for all documents with "type":"message"? (without pulling all documents with type:message)
Thanks
Create a view that emits all doc ids. The view keys will be used for sorting automatically.
function(doc) {
if(doc.type && doc.type === 'message'){
emit(doc._id, null);
}
}
Then execute a query: http://host/yourdb/_design/yourdesigndoc/_view/viewname?limit=10&include_docs=true&descending=true
Because you want the full document, we didn't included anything as value in the view. Instead, we add include_docs=true
to fetch every full document for the view entries.
Note that there is also a builtin view that does the same: http://host/yourdb/_all_docs?limit=10&include_docs=true&descending=true
PS: You should be aware of the fact that CouchDB by default uses UUIDs as IDs, which will render the sorting more or less useless, if you really want to get the latest docs. Either provide your own incremental IDs (what about distribution/replication?) or use a new field that stores the time the doc has been created and use in the view as well.
If your docs have a created
field (i.e. UNIX timestamp, JavaScript Date.now() or even a RFC 3339-like string), you can build an index on these values.
Here is the time-based view:
function(doc) {
if(doc.type && doc.type === 'message' && doc.created){
emit(doc.created, null);
}
}
Note that we will not emit the doc._id itself. However, CouchDB stores the doc._id
where the data came from for each emitted key/value pair automatically, so we can again use include_docs=true
to fetch the complete docs.
Query http://host/yourdb/_design/yourdesigndoc/_view/viewname?limit=10&include_docs=true&descending=true
If the IDs of your documents are already incremental, instead of the default UUIDs of CouchDB, you do not even need to define a view, you can just use the default _all_docs view, e.g.
http://couchdb_host/your_db/_all_docs?limit=10&descending=true&include_docs=true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With