coder25
coder25

Reputation: 2393

limit the result using cts:collection-match in marklogic

I have 2 collections in collections.

This has 10 documents with id

test1_1
test1_2
.....
test1_10

This has 20 documents with id as follows

test2_1
test2_2
.....
test2_20

Query:

let $result := cts:collection-match("/test/*")
let $id :=(
  fn:distinct-values(
    for $doc in fn:collection(result)
    order by $doc//timestamp descending
    return $doc//timestamp/text()
  )[1 to 5]
)
return $id

I want to return the top 5 documents from each collection descending order of timestamp but it returns only 5 documents not 10 i.e. top 5 from each collection

Upvotes: 1

Views: 540

Answers (1)

wst
wst

Reputation: 11771

When $result is a sequence of greater than one item, writing for $doc in fn:collection($result) aggregates all of the documents from multiple collections into a single sequence. You need to iterate over collections first, then iterate over the values in each collection, ordered and limited.

let $collections := cts:collection-match("/test/*")
let $id :=         
    for $collection in $collections
    return 
      fn:distinct-values(
        for $doc in fn:collection($collection)
        order by $doc//timestamp descending
           return $doc//timestamp/string()
      )[1 to 5]
return $id

Upvotes: 3

Related Questions