I've some CosmosDB documents like the following
{
  "ProductId": 1,
  "Status": true,
  "Code": "123456",
  "IsRecall": false,
  "ScanLog": [
    {
      "Location": {
        "type": "Point",
        "coordinates": [
          13.5957758,
          42.7111538
        ]
      },
      "TimeStamp": 201602160957190600,
      "ScanType": 0,
      "UserId": "1004"
    },
    {
      "Location": {
        "type": "Point",
        "coordinates": [
          13.5957907,
          42.7111359
        ]
      },
      "TimeStamp": 201602161246336640,
      "ScanType": 0,
      "UserId": "1004"
    }
  ]
}
How can I order the query results by the TimeStamp property? I've tried using this query
SELECT c.Code, b.TimeStamp FROM c JOIN b IN c.ScanLog ORDER BY b.TimeStamp
but I receive this error
Order-by over correlated collections is not supported.
What is the correct way to do this?
JOINs with ORDER BY are currently not supported.
However, here is a user defined function (UDF) that will do the trick:
function sortScanLog (scanLog) { 
  function compareTimeStamps(a, b) {
    return a.TimeStamp - b.TimeStamp;
  }
  return scanLog.sort(compareTimeStamps);
}
You use with a query like this:
SELECT c.ProductId, udf.sortScanLog(c.ScanLog) as ScanLog FROM c
If you want the opposite sort order, simply swap the a and b. So, the signature of the compareTimeStamps inner function would be:
function compareTimeStamps(b, a)
Alternatively, you can sort client-side after the results are returned.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With