8

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

0xdeadbeef
  • 4,090
  • 8
  • 33
  • 37

1 Answers1

15

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);
Nick Perkins
  • 8,034
  • 7
  • 40
  • 40
b_erb
  • 20,932
  • 8
  • 55
  • 64
  • Thanks a lot, just what I wanted. – 0xdeadbeef Jan 23 '11 at 15:47
  • I'd probably prefer adding a new document for each status. This will lead to more documents, but tends to prevent conflicts and allow a scalabale design with 'eventual consistent' statuses. Each document that must at least contain status message, user, time and internal meta data you might perhaps require. – b_erb Jan 24 '11 at 07:39
  • I have a document for each user and a nested document for status inside the user document. I'm still having trouble retrieving just the recent status only. I can probably deal with it at application level, but im trying to learn todo it this way. – 0xdeadbeef Jan 24 '11 at 09:31
  • http://wiki.apache.org/couchdb/HTTP_view_API#Querying_Options - limit is your friend (sort by date descending and only take the first n elements). – b_erb Jan 24 '11 at 11:32
  • how would the url look like for querying by datetime and user? – OrangePot Jun 16 '17 at 22:40