有一个包含4个文档的集合。我想检索具有最新时间戳的文档。
下面的查询有助于按降序排序,但我希望 最新修改的文档
for $doc in fn:collection("/test") order by $doc//timestamp descending return $doc//id/text(),",",$doc//timestamp/text())
输出
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
for循环已经在生成一个序列,所以只需获取第一项。因此,如果不想查询不需要的文档的值,请将查询的输出呈现部分移动到单独的表达式中。
let $latest := (for $doc in fn:collection("/test") order by $doc//timestamp descending return $doc)[1] return $latest//id/text(),",",$latest//timestamp/text())
现在,如果上有范围索引 timestamp 的类型 xs:dateTime ,您可以选择最新的文档,而无需先将所有这些文档加载到内存中并进行排序。但是,您可能需要更换 $doc//timestamp 具有 $doc/path/to/timestamp (无双斜杠),以便查询优化器自动使用范围索引。
timestamp
xs:dateTime
$doc//timestamp
$doc/path/to/timestamp