skip to Main Content

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


  1. 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

    Login or Signup to reply.
  2. 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!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search