Search code examples
couchbasecouchbase-litecouchbase-viewnosql

How to get the latest document in couchbase bucket?


I have a activity bucket in my couchbase-db and I need to retrieve the latest document for different types, My initial approach was this:

Document Format : [ id , { val.time ,val.type, val.load } ]

And then I wrote different views to Map a specific val.type and I used reduce to get the latest val.time, However I have the problem of views not being updated ( Cause apparently the Map is only called on new or changed documents and this approach needs all of the documents to be mapped and reduced.)

What is the best practice / approach for time-based data on Couchbase ( NoSQL ) databases ?


Solution

  • You can access the documents by time with a simple view like this:

    1. Convert your time to an integer value. Eg using the parse() method. http://www.quackit.com/javascript/javascript_date_and_time_functions.cfm

    2. Use this integer value as the key to your view. You can then access the first or last document.

    3. If you always need the last document it's faster to negate the time value, so the largest times are at the start of the index.