Home > Back-end >  `findMany` where `id` ends with elements of an array
`findMany` where `id` ends with elements of an array

Time:11-01

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?

CodePudding user response:

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.

db.collection.find({
  $expr: {
    "$anyElementTrue": {
      "$map": {
        // your input array
        "input": [
          "ace",
          "acb",
          "acc",
          "aca"
        ],
        "as": "suffix",
        "in": {
          $ne: [
            -1,
            {
              "$indexOfCP": [
                "$id",
                "$$suffix"
              ]
            }
          ]
        }
      }
    }
  }
})

Mongo Playground

CodePudding user response:

You can try this:

await prisma.documents.findMany({
  where: {
    OR: ['ace', 'acb', 'acc', 'aca'].map(element => ({
      id: {
        endsWith: element
      }
    }))
  }
});

I'm using Postgres, don't know if Prisma working the same on MongoDB but hope it help!

  • Related