Sorting Dates in CouchDB Views

2019-02-09 14:19发布

问题:

I have a nested JSON object for the key status below:

{
"2011-01-19 09:41:00 AM": "Prototyping status application",
"2011-01-20 09:41:00 AM": "Playing with CouchDB"
}

It's a little application where user can enter his/her status. I want to get the most recent status from it. Is this approach good for such applications, or do I have to have a key that defines sort order?

What's the best way to get the most recent date?

Thanks

回答1:

Use view collation and emit a complex key.

If you first want to sort by user, then by time, use this as key. If you only want to sort by time, omit the username as key.

If you're using Date-style values:

emit([Date.parse(doc.created_at).getTime(), doc.username], doc);

If you use a date format that is already sortable lexicographically:

emit([doc.created_at, doc.username], doc);