Search code examples
xquerymarklogic

return latest document based on a element in marklogic


There is a collection with 4 documents. I want to retrieve the document with latest timestamp.

The below query helps to sort in descending order but I want the latest modified document

 for $doc in fn:collection("/test")
 order by $doc//timestamp descending
 return $doc//id/text(),",",$doc//timestamp/text())

Output

1234, 2018-03-05T11:29:42.722Z
 5678,2018-03-05T11:29:42.715Z
 8976,2018-02-05T11:28:42.710Z
 8976,2018-02-04T11:28:42.716Z

Solution

  • Your for loop is already generating a sequence, so all you need to do is take the first item. And so you don't end up querying values for documents you don't want, move the output rendering portion of the query into a separate expression.

    let $latest :=
      (for $doc in fn:collection("/test")
      order by $doc//timestamp descending
      return $doc)[1]
    return $latest//id/text(),",",$latest//timestamp/text())
    

    Now, if there is a range index on timestamp of type xs:dateTime, you can select the most recent document without first loading all those document into memory and sorting. However, you may have to replace $doc//timestamp with $doc/path/to/timestamp (no double-slash) for the query optimizer to automatically use a range index.