Sort Array of objects by unix timestamp

Hey guys,

I'm storing sensor data in a Cloudant DB. Every document consists of the 63 sensor values and a unix timestamp. When querying all the documents from the DB, I realized that those documents are not chronologically ordered.

Can anyone help me with a function to sort my array according to its timestamps?
The array looks like this:

The payload is an array containing all the documents of the DB. Each document is an object of Cloudant DB specific values (_id and _rev), "TS" = timestamp and "Values". "Values" is again an array of objects of the format {sensorID:temperature}.

My goal is to sort the array containing all documents according to their timestamps.

1 Like

Have you tried changing your db query to include “ORDER BY” ?

I haven't seen that. I am not sure if you mean the SQL "ORDER BY"? Cloudant is a NoSQL DB and I use the built in Node-RED Node to connect and query my NoSQL DB

I meant generically (i was on a train)

{
  "selector": {
    "date": {
      "$gt": 2010
    }
  }, 
  "fields": ["_id", "_rev", "insert_ts", "name"], //
  "sort": [{"insert_ts": "asc"}]
}
4 Likes

This definitely makes sense. It would require tho that I launch the http request myself using the "http request" node instead of the built in cloudant node since there's no such option from the cloudant node directly.

The sort key has an array as value so I assume that I can set several sorting objects? I firstly want to sort all documents by their timestamp and then 2ndly within each document sort the Values according to a predefined csv file such that "Values array" sorts its objects according to the sensors position in real life. Any hint on how to solve the 2nd problem of sorting according to a predefined csv structure?

There are several other cloudant nodes in flows.nodered.org - I'm sure one will allow sorting.

I agree that the sorting should be done in the database, not after the fact -- but if you cannot find a way to have the database do it, you can always use the sort node:

image

1 Like

I tried and it works apart from the sorting. When I try to sort the output, it fails (see screenshots). I stick to all the introductions on the Cloudant documentation and follow your example. Do you see why I get a HTTP 400 back?