for $key in $keysForDocs return $dtbIndex/doc-to-bundle-index-entry[@key eq $key]/bundles/bundle ! string(.)
You can probably save time by omitting the loop:
$dtbIndex/doc-to-bundle-index-entry [@key = $keysForDocs]/bundles/bundle ! string(.)
Did you check if $dtbIndex is inlined at compile time?