I have an array of strings that are end part of document IDs
const arr = ['ace', 'acb', 'acc', 'aca'];
const documents = [
{ id: 'xxxxxxxace' },
{ id: 'xxxxxxxacb' },
{ id: 'xxxxxxxacc' },
{ id: 'xxxxxxxaca' }
];
I need a query that would return all documents whose IDs ends with either of arr
elements.
The only way I could do this is by iterating over arr
and calling findFirst
with endsWith
for each array element.
Are there better ways?
2
Answers
Use
$indexOfCP
to check whether the suffix is located in the id. Apply$map
for the array-wise oepration. Finally use$anyElementTrue
to return the doc for matching any one of the cases.Mongo Playground
You can try this:
I’m using Postgres, don’t know if Prisma working the same on MongoDB but hope it help!