How to sort documents by the lastModified timestamp

204 views
Skip to first unread message

Andrew

unread,
Dec 19, 2014, 7:07:00 AM12/19/14
to mobile-c...@googlegroups.com
Hi - i have a collection of documents sharing a lastModified timestamp field in a standard format going down to the second granularity.

Is it possible to design a view that will return these documents sorted by the lastModified property in either increasing or decreasing order?


Jens Alfke

unread,
Dec 19, 2014, 11:44:17 AM12/19/14
to mobile-c...@googlegroups.com

On Dec 19, 2014, at 4:07 AM, Andrew <andrzej....@gmail.com> wrote:

Hi - i have a collection of documents sharing a lastModified timestamp field in a standard format going down to the second granularity.
Is it possible to design a view that will return these documents sorted by the lastModified property in either increasing or decreasing order?

Sure. Just have the map function emit the lastModified property as the key.
To query in decreasing order, set the Query's .descending property.

—Jens

Andrew

unread,
Dec 20, 2014, 7:40:45 AM12/20/14
to mobile-c...@googlegroups.com
I should have been more precise in my question.

If the timestamp has the following format "dd mmm eye hh:mm:ss" for example "10 Oct 2014 12:20:21"

Will the sorting on key be able to figure out it is dealing with a timestamp rather than a simple string and sort accordingly ? I am sensing it will do alphabetical sort instead?

Andrew

Jens Alfke

unread,
Dec 22, 2014, 12:20:47 AM12/22/14
to mobile-c...@googlegroups.com

On Dec 20, 2014, at 4:40 AM, Andrew <andrzej....@gmail.com> wrote:

Will the sorting on key be able to figure out it is dealing with a timestamp rather than a simple string and sort accordingly ?

No. JSON has no date type; this would be stored as a string and sorted accordingly.

You should emit a date format that sorts correctly alphabetically, such as the ISO-8601 format that's the de facto standard for JSON. It looks like "yyyy-MM-dd'T'HH:mm:ss.SSSZ", i.e. "2014-12-21T17:35:12.874Z". If you're using the iOS version of Couchbase Lite, you can use the CBLJSON class to convert to/from this format.

It's most efficient if the documents store the dates in this format, but if they don't, you can work around it by having your map function do the conversion. Just parse the dates from your format and then re-emit them in the ISO-8601 format and emit that string as the key.

(Actually if you're going to convert in the map function, it's even more efficient to parse the dates into a numeric form like "seconds since 1/1/1970" and just emit that number. It's more compact, and faster for the index to sort.)

—Jens
Reply all
Reply to author
Forward
0 new messages