sharepoint online – dynamically filter documents in a document library based on their folders and subfolders

If there are a limited number of sites, you can use the search.

Who will be the user? A "power user" who can be shown how to write search queries? If not, a user-friendly interface takes on additional tasks.

Search:

(path:"https://yourDomain/HR/policies/external" OR path:"https://yourDomain/HR/general document/external") AND isdocument=1

The search can be browsed through Web Parts, custom Web Parts, or custom code using REST queries.

From REST:

https://yourDomain/_api/search/query?querytext='(path:"https://yourDomain/HR/policies/external" OR path:"https://yourDomain/HR/general document/external") AND isdocument=1'

REST to search for a keyword in the path:

https://yourDomain/sites/yourSite/_api/web/lists/getbytitle('Documents')/items?$filter=substringof('external',FileDirRef)&$select=FileDirRef,FileRef,Title

Second, even if we find a way to perform such filtering from multiple document libraries.

Search by path: or other metadata can search across all sites.